Python:Relative import 相對路徑 ValueError: Attempted relative import in non-package


使用相對的的 import 方式,只能在包里面;這樣 “.” 就會按照name 找路徑;

如果主main運行的話__name__ = "__main__" 就找不到路徑了。

包含相對路徑import 的python腳本不能直接運行,只能作為module被引用。原因正如手冊中描述的,所謂相對路徑其實就是相對於當前module的路徑,但如果直接執行腳本,這個module的name就是“main”, 而不是module原來的name, 這樣相對路徑也就不是原來的相對路徑了,導入就會失敗,出現錯誤“ValueError: Attempted relative import in non-package”

Note that both explicit and implicit relative imports are based on the name of the current module. Since the name of the main module is always"__main__", modules intended for use as the main module of a Python application should always use absolute imports.

只能 從包外面 觸發里面的相對路徑調用;

eg:執行外面的 z.py 觸發里面 top/sub1/m1.py 使用相對路徑

GitHub 示例文件下載 rar_down

#\relative_import\\top\sub1\m1.py
print 'i am m1 \nfrom . import m2 \n...from ..sub2 import sub2_sub'
from . import m2  
from ..sub2 import sub2_sub

from . import m2 #同級目錄

from ..sub2 import sub2_sub # 上級目錄

#\relative_import\z.py  
from top.sub1 import m1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM