[英]Understanding absolute and relative imports
我正在嘗試從另一個模塊中的文件導入函數,但始終收到以下錯誤。
ValueError: Attempted relative import in non-package
我看過很多文章說絕對而不是相對導入,但是會出現錯誤
ImportError: No module named app.main.events
我的檔案結構
\_ dir
\_ __init__.py
\_ app
\_ main
\_ __init__.py
\_ events.py
\_ game
\_ __init__.py
\_ run.py
events.py
def my_function():
do something....
run.py
from ..main.events import my_function
# returns
Attempted relative import in non-package
from app.main.events import my_function
# returns
No module named app.main.events
我看不到我出了什么問題...這可能很簡單。
只要您在包中使用相對導入就可以,並且是顯式的,例如from . import foo
from . import foo
。 文章所說的不好是,當您import foo
並依賴位於同一目錄中的名為foo.py的文件時。
如果直接執行python run.py
,則解釋器不知道run.py是較大軟件包的一部分。 您要么需要使用python -m run.main
作為模塊運行它,要么(在我看來)最好在setup.py中設置一個入口點 。
也記不清是否有必要,但是您的app
子目錄中可能缺少__init__.py。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.