这是我的项目结构。[~/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", line 3, in <module> from .utils import spam, 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)!>>> 我相信我的问题来自没有完全理解PYTHONPATH,我尝试谷歌搜索,但我还没有找到我的答案......请提供任何见解。
1 回答
炎炎设计
TA贡献1808条经验 获得超4个赞
当你从一个包中导入时,你是从__init__.py那个包的......
所以在你的 utils 包中,你__init__.py是空的。
尝试将此添加到您的 utils/__init__.py
print("utils/__init__.py")
from . import eggs
from . import spam
现在,当您说from utils import eggs, spam要从utils 包的init .py 中导入我在其中导入的内容时。
此外,在 pystructure.py
改变这个
from .utils import eggs, spam
进入这个
from utils import eggs, spam
添加回答
举报
0/150
提交
取消