[英]Python - import from a file when a package has the same name
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. 启动python项目时,我做了一些愚蠢的事情:我将主文件命名为project.py,并将一堆逻辑存储在一个也称为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. 问题出在这里:现在我需要从project.py导入main函数。 But every time I try to import it, python tries to import the package instead of the module.
但是每次我尝试导入它时,python都会尝试导入包而不是模块。
>>> 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? 有什么方法可以解决此问题而无需重命名文件夹或文件?
Right now, my solution is to move the logic from project.py to a new file: 现在,我的解决方案是将逻辑从project.py移到新文件:
project.py
project/
main.py
contents of project.py: project.py的内容:
import project.main
if __name__ == "__main__":
project.main.main()
Then I can import project.main.main() directly. 然后,我可以直接导入project.main.main()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.