亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python項目結構,項目主文件導入助手

Python項目結構,項目主文件導入助手

慕斯709654 2021-12-09 10:39:13
這是我的項目結構。[~/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 


查看完整回答
反對 回復 2021-12-09
  • 1 回答
  • 0 關注
  • 231 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號