這是我的項目結構。[~/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
提交
取消