[英]Python intra-package references not working
我正在努力使用包內引用。 這是我正在關注的文檔https://docs.python.org/3.9/tutorial/modules.html#intra-package-references
我正在做一個小測試:
test/
__init__.py
module_a/
__init__.py
script_a.py
( from test.module_b import script_b )
module_b/
__init__.py
script_b.py
( def something(): print("something") )
但是我的導入不起作用,並且出現了這個錯誤
Exception has occurred: ModuleNotFoundError
No module named 'test'
File "/Users/nacho/Desktop/test/module_a/script_a.py", line 1, in <module>
from test.module_b import script_b
我究竟做錯了什么?
我沒有使用任何框架。 使用此命令只需簡單的 python 3.9
python3 script_a.py
我沒有安裝測試 package o 使用 -m 開關。
問候!
它不起作用,因為在 Python 的import paths上找不到 package test
。 你有(至少)四個選項來解決這個問題:
test
目錄的目錄運行腳本,即python test/module_a/script_a.py
。 這樣,在test
package 中使用的所有導入都必須是絕對的,即形式from test.module_b import script_b
(而不是from..module_b import script_b
)。-m
開關運行 package ,同樣從包含test
目錄的目錄: python -m test.module_a
。 您需要在module_a
中提供一個額外的__main__.py
文件來調用所需的功能。 這樣你也可以使用相對導入,即.
和..
PYTHONPATH
指向包含test
的目錄: PYTHONPATH=/path/to/test python script_a.py
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.