我无法完成这项工作..
我的结构是:
program_name/
__init__.py
setup.py
src/
__init__.py
Process/
__init__.py
thefile.py
tests/
__init__.py
thetest.py
测试.py:
from ..src.Process.thefile.py import sth
运行: pytest ./tests/thetest.py
来自 program_name
给出:
ValueError: attempted relative import beyond top-level package
我也尝试了其他方法,但收到各种错误。
但我希望以上内容能够奏效。
原文由 George 发布,翻译遵循 CC BY-SA 4.0 许可协议
ValueError:尝试在非包中进行相对导入
声明您正在尝试在模块中使用相对导入,这些导入将用于包,即使其成为一个包添加
__init__.py
并调用thetest.py
包裹。直接从解释器运行thetest.py
是行不通的。建议 1 :
当前
tests
目录有一个__init__.py
文件,但不允许您将其作为模块运行(通过 shell)- 要使当前(相对)导入工作,您需要将其导入外部(打包)文件/模块 - 让我们创建一个main.py
(可以随意命名):src/Process/ thefile.py :
测试/ thetest.py :
主要文件:
执行 main.py :
建议 2 :
按照以下方式执行根目录上方的文件,即
program_name/
的上一层:附言。相对导入是针对包的,而不是模块。