[英]Imports work when using installed Python package but not in source code
我試圖繞過這個 ImportError。 我創建了一個 Python 腳本,打包並上傳到 PyPi。 當我導入 package 並運行它時,一切正常。 但是,當我嘗試運行我的 Python 腳本的源代碼時,我收到此錯誤: ImportError: attempted relative import with no known parent package
。
proj
|---src
| |---package_name
| | |---__init__.py
| | |---class.py
| | |---func.py
在 class.py 中,我從 func.py 導入函數,如下所示: from.func import *
。 當我嘗試運行python3 class.py
時,這會導致錯誤。 我無法理解的是,為什么當我從 Pypi 安裝 package,將其導入另一個 Python 文件並在那里使用 ZA2F2ED4F8EBC2CBB4C21A29DC40AB61D 時,這不會導致任何問題。
Well python does not lie, there is no known parent package - you must tell python that the script you are trying to run is part of a package. 嘗試cd
到package_name
目錄,然后發出:
python3 -m package_name.class # note no py and the -m 'module' switch
另外:您是否將您的模塊命名為 class? 這可能會導致令人討厭的意外 -切勿將 python 保留關鍵字用於模塊/包/變量名稱
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.