Python包内引用不起作用
我正在努力处理包内引用。这是我正在遵循的文档 我正在用这个做一个小测试:Python包内引用不起作用,python,python-3.x,module,Python,Python 3.x,Module,我正在努力处理包内引用。这是我正在遵循的文档 我正在用这个做一个小测试: 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(): p
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
我没有安装使用-m开关的测试包
问候 它不起作用,因为在Python上找不到包
test
。您有(至少)四个选项来解决此问题:
test
目录的目录运行脚本,即python测试/module\u a/script\u a.py
。这样,测试
包中使用的所有导入必须是绝对的,即形式为test.module\u b import script\u b(而不是..module\u b import script\u b)中的
test
目录的目录运行包:python-m test.module\u a
。您需要在模块a
中提供一个调用所需功能的附加文件。这样,您还可以使用相对导入,即
和。
test
的目录:PYTHONPATH=/path/to/test python script\u a.py
你是如何运行python的?请包含完整的命令。您是否安装了
测试
软件包?您是否从包含测试的目录运行?您是否使用了-m
开关?嗨!谢谢你的评论!我用这些新信息编辑了这个问题。当做
python3 script_a.py