【问题标题】:VSCODE pytest not constructing sys.path the same as command line pytestVSCODE pytest 不构造 sys.path 与命令行 pytest 相同
【发布时间】:2020-11-05 15:07:04
【问题描述】:

使用 VSCODE python 扩展运行 pytest 时出现导入错误。从命令行运行 pytest 时,我没有收到错误消息。

我有一个带有以下设置的 python 2.7 项目。

provision/
|-- venv/
|-- requirements.txt
|-- model_config/
|   |-- ifrs9model_config/
|   |-- |-- __init__.py
|   |-- |-- model_config.py
|   |
|   |-- data/
|   |   |-- input.csv
|   | 
|   |-- tests/
|   |   |--conftest.py
|   |   |--test_model_config.py
|   |   
|   |-- setup.py
|   |-- README

我已将软件包 ifrs9model_config 安装到 venv 中。这允许我在 conftest.py 文件中导入 ifrs9model_config,如下所示:

from ifrs9model_config import model_config

当我直接运行 conftest.py 时,它工作正常。当我从命令行运行 pytest 时(激活 venv 之后),它也可以正常工作。但是当我使用 VSCODE 的 python 扩展运行 pytest 时,我得到了错误:

ImportError while loading conftest '/sasdata/Lev3/apps/provision/model_config/tests/conftest.py'.
tests/conftest.py:6: in <module>
    from ifrs9model_config import model_config
E   ImportError: No module named ifrs9model_config

vscode pytest 正在运行以下命令:

python /home/<userid>/.vscode-server-insiders/extensions/ms-python.python-2020.10.332292344/pythonFiles/testing_tools/run_adapter.py discover pytest -- --rootdir /sasdata/Lev3/apps/provision/model_config -s --cache-clear tests

打印 sys.path(主要来自 conftest.py 脚本)后,我注意到当 VSCODE 运行 pytest 时,pytest rootdir (/sasdata/Lev3/apps/provision/model_config) 不包含在 sys.path 中。但是,当我使用此命令从命令行运行 pytest 时,它会包含在内:

pytest --rootdir /sasdata/Lev3/apps/provision/model_config/ -s --cache-clear tests

run_adapter.py 脚本确实将一些目录插入到 sys.path 值中,但这并不能解释为什么缺少上述内容。

现在,如果我在 conftest.py 文件中添加这样的一行:

sys.path.append('/sasdata/Lev3/apps/provision/model_config/')

它在 VSCODE 中工作。

我对此特别困惑,因为我认为通过使用 setup.py 和“pip install -e.”将 ifrs9model_config 包安装到 venv 中,该模块将可用于 venv 中的任何 python 会话?

我还读到,弄乱 sys.path 是不好的形式,无论哪种方式,我都不是特别热衷于将代码添加到我的脚本中,只是为了帮助 VSCODE 运行。

为什么从 VSCODE 和命令行执行 pytest 时 sys.path 会有所不同?解决我的错误的最佳方法是什么?

【问题讨论】:

  • 您没有做错任何事情,可编辑安装是最好的方法。我的猜测是 VSCode 不使用来自 venv 的可执行文件 - 你是如何在 VSCode 中配置解释器的?
  • 谢谢。我有同样的想法,但我仔细检查过,它是从 venv 运行的。我已经将解释器配置为运行 venv 可执行文件(我们甚至没有在服务器的通用 python 安装上安装 pytest)。这很奇怪,因为 sys.path 与我在 venv 中运行任何东西时完全相同,只是它删除了模块的路径。
  • 现在,我刚刚添加了一行,将模块路径(返回)显式添加到 sys.path 中,以使 VSCODE 测试正常工作。手动运行 pytest 稍微好一些,但我相信有更好的方法。

标签: python-2.7 visual-studio-code pytest vscode-python


【解决方案1】:

我刚刚在基于 devcontainer 的 Python 项目中遇到了同样的问题,并通过配置插件使用哪个 pytest 可执行文件(在 .vscode/settings.json 中)解决了这个问题:

{
  "python.testing.pytestPath": "/usr/local/bin/pytest"
}

【讨论】:

  • 显然这个路径应该指向你的 pytest 可执行文件,它很可能在你的 venv 中。您可以通过which pytest 找到它
猜你喜欢
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
  • 2020-11-27
  • 2018-08-14
  • 2017-05-25
  • 1970-01-01
  • 1970-01-01
  • 2022-10-21
相关资源
最近更新 更多