繁体   English   中英

Python 包内引用不起作用

[英]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 你有(至少)四个选项来解决这个问题:

  1. 包含test目录的目录运行脚本,即python test/module_a/script_a.py 这样,在test package 中使用的所有导入都必须是绝对的,即形式from test.module_b import script_b (而不是from..module_b import script_b )。
  2. 通过-m开关运行 package ,同样从包含test目录的目录: python -m test.module_a 您需要在module_a中提供一个额外的__main__.py文件来调用所需的功能。 这样你也可以使用相对导入,即. ..
  3. 安装整个 package ,然后您可以从任何地方从命令行运行它(使用(2)中描述的步骤)。
  4. 修改PYTHONPATH指向包含test的目录: PYTHONPATH=/path/to/test python script_a.py

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM