这是我的项目结构.
[~/SandBox/pystructure]:$tree.├── pystructure│ ├── __init__.py│ ├── pystructure.py│ └── utils│ ├── eggs│ │ ├── base.py│ │ └── __init__.py│ ├── __init__.py│ └── spam.py├── README.md└── requirements.txt3 directorIEs,8 files
这些是文件的内容,
[~/SandBox/pystructure]:$cat pystructure/utils/spam.py def do(): print('hello world (from spam)!')[~/SandBox/pystructure]:$cat pystructure/utils/eggs/base.py def do(): print('hello world (from eggs)!')[~/SandBox/pystructure]:$cat pystructure/utils/eggs/__init__.py from .base import do[~/SandBox/pystructure]:$cat pystructure/pystructure.py #!/usr/bin/python3from .utils import spam,eggsdef main(): spam.do() eggs.do()if __name__ == '__main__': main()
但是,当我尝试像这样运行应用程序时,出现此错误,
[~/SandBox/pystructure]:$python3 pystructure/pystructure.py Traceback (most recent call last): file "pystructure/pystructure.py",line 3,in <module> from .utils import spam,eggsModuleNotFoundError: No module named '__main__.utils'; '__main__' is not a package
或者当我尝试从创建文件的目录中运行代码时(这不是我的期望,因为我想将其作为服务或使用cron来运行),
[~/SandBox/pystructure]:$cd pystructure/[~/SandBox/pystructure/pystructure]:$python3 pystructure.py Traceback (most recent call last): file "pystructure.py",eggsModuleNotFoundError: No module named '__main__.utils'; '__main__' is not a package
但是,如果我导入它,它确实可以工作(但是只能从基本目录中…)
[~/SandBox/pystructure/pystructure]:$cd ..[~/SandBox/pystructure]:$python3Python 3.6.7 (default,Oct 22 2018,11:32:17) [GCC 8.2.0] on linuxType "help","copyright","credits" or "license" for more information.>>> from pystructure import pystructure>>> pystructure.main()hello world (from spam)!hello world (from eggs)!>>>
(如果我尝试从它所在的目录中导入它,则会收到此错误),
[~/SandBox/pystructure]:$cd pystructure/[~/SandBox/pystructure/pystructure]:$python3Python 3.6.7 (default,"credits" or "license" for more information.>>> import pystructureTraceback (most recent call last): file "<stdin>",line 1,in <module> file "~/SandBox/pystructure/pystructure/pystructure.py",eggsimportError: attempted relative import with no kNown parent package>>>
我相信我的问题来自对PYTHONPATH的不完全了解,我尝试使用Google谷歌搜索,但是我还没有找到答案…请提供任何见解.最佳答案从程序包导入时,就是从该程序包的__init__.py导入….
因此在您的utils软件包中,您的__init__.py为空.
尝试将其添加到您的utils / __ init__.py
print("utils/__init__.py")from . import eggsfrom . import spam
现在,当您说从utils导入鸡蛋时,您是在说垃圾邮件,是从utils包的init.py中导入我在其中导入的内容.
另外,在pystructure.py中
改变这个
from .utils import eggs,spam
进入这个
from utils import eggs,spam
总结 以上是内存溢出为你收集整理的Python项目结构,项目主文件导入助手 全部内容,希望文章能够帮你解决Python项目结构,项目主文件导入助手 所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)