Python-包名称相同时从文件导入 [英] Python - import from a file when a package has the same name
问题描述
启动python项目时,我做了一些愚蠢的事情:我将主文件命名为project.py,并将一堆逻辑存储在一个也称为project的程序包中.这是目录结构:
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
这里是问题:现在我需要从project.py导入main函数.但是每次我尝试导入它时,python都会尝试导入包而不是模块.
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?
推荐答案
现在,我的解决方案是将逻辑从project.py移至新文件:
Right now, my solution is to move the logic from project.py to a new file:
project.py
project/
main.py
project.py的内容:
contents of project.py:
import project.main
if __name__ == "__main__":
project.main.main()
然后我可以直接导入project.main.main().
Then I can import project.main.main() directly.
这篇关于Python-包名称相同时从文件导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!