Python/Pytest - 将模块导入到文件中,与目录中的位置无关?

标签 python pytest

我正在尝试在我的项目中设置 pytest,目录结构如下所示。

├── 
├── README.md
├── my_code
│   ├── __init__.py
│   ├── __main__.py
│   └── target_file.py
└── tests
│   ├── __init__.py
│   └── test_one.py

在我的 test_one.py 中,我使用

导入 target_file.py
import sys
import os
sys.path.insert(0, "my_code")

如果我从根目录中的命令行运行 pytest ,这可以工作。但是,如果我cd进入不同的目录,例如进入tests,我会收到一条错误消息,指出模块my_code没有属性bla bla bla。我认为这是因为我导入的方式取决于我在目录中的实际位置。因此,如果我位于 tests 目录中,那么它将尝试从 /root/tests/my_code 导入,而该目录并不存在。有没有办法将 target_file.py 导入到 test_one.py 中,这样无论我在哪里,我都可以在命令行上运行 pytest,以便我的测试会跑?就目前情况而言,我必须转到根目录才能使导入正常工作。

最佳答案

将项目主目录的完整路径添加到 sys.path,而不仅仅是相对路径。 在linux下,从/开始到包含自述文件的目录

关于Python/Pytest - 将模块导入到文件中,与目录中的位置无关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50431869/

相关文章:

python - PyAutoGui 对于locateOnScreen 始终不返回任何内容

python - Flask 和 gunicorn,多个模块 : circular imports - not all routes accessible

github - 使用 Cloud Build Trigger 对 Github Pull Request 中提到的文件运行 Pytest

python - 我将如何对这样的代码进行单元测试?

python - 使用 mock 和 pytest 在 python 中模拟装饰器

python - 值错误: invalid literal for int() with base 10 on Alexnet

python - 设置空闲线程/信令线程

python - 在python中打印字典的原始输入顺序

python - pytest 和 tox 的环境变量

python - VSCode + Pytest : "Error: TypeError: Cannot read property ' $' of undefined"