Python - import from a file when a package has the

2019-09-06 15:39发布

问题:

I did something silly when I started my python project: I named my main file project.py, and I stored a bunch of logic in a package that is also called project. Here's the directory structure:

project.py
project/
    other files

Here's the problem: Now I need to import the function main from project.py. But every time I try to import it, python tries to import the package instead of the module.

>>> from project import main
AttributeError: 'module' object has no attribute 'main'
>>> import project
>>> print(project)
>>> <module 'project' from 'c:\temp\project\__init__.pyc'>

Is there any way to fix this without renaming either the folder or the file?

回答1:

Right now, my solution is to move the logic from project.py to a new file:

project.py
project/
    main.py

contents of project.py:

import project.main
if __name__ == "__main__":
    project.main.main()

Then I can import project.main.main() directly.



标签: python import