[英]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.