You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VSCode运行pytest报错No module named 'src'问题排查求助

问题现象

在cmd命令行中使用pytest执行单元测试可正常运行,但在VSCode中导入项目主文件时出现导入错误:ModuleNotFoundError: No module named 'src'。

项目目录结构
MATCHING_CC/
├─ pytest.ini
├─ __init__.py               (空文件)
├─ conftest.py               (空文件)
├─ src/
│  ├─ __init__.py           (空文件)
│  ├─ conftest.py           (空文件)
│  ├─ matching_ingr_zing.py
│  └─ services/
│     ├─ __init__.py       (空文件)
│     ├─ ElasticSearch.py
│     ├─ ingredient_extractor_for_search.py
│     ├─ metrics.py
│     └─ stop_word_matching.py
├─ models/        (存放训练好的模型的目录)
└─ tests/
   ├─ __init__.py                (空文件)
   ├─ test_services/
   │  ├─ __init__.py            (空文件)
   │  ├─ test_elastic_search.py
   │  ├─ test_ingredient_extractor_for_search.py
   │  └─ test_metrics.py
   └─ test_src/
      ├─ __init__.py                (空文件)
      └─ test_matching_ingr_zingr.py
错误原因
  • 命令行执行pytest时,pytest会自动将当前执行命令所在的根目录(即MATCHING_CC/目录)加入Python模块搜索路径sys.path,因此可以正常识别src目录下的模块,测试运行无异常。
  • VSCode中运行代码、调试测试时,默认的Python模块搜索路径未将项目根目录MATCHING_CC/纳入,解释器无法在搜索路径中找到src模块,因此抛出导入错误。
修复方法

可任选以下一种方案修复:

  • 方案1:配置VSCode工作区设置
    在项目根目录下新建.vscode/settings.json文件,写入以下配置,指定Python解析和测试时的模块搜索路径:
    {
      "python.testing.pytestArgs": ["."],
      "python.analysis.extraPaths": ["${workspaceFolder}"]
    }
    
    配置完成后重启VSCode窗口即可生效。
  • 方案2:修改pytest.ini配置
    在项目根目录已有的pytest.ini文件中添加路径配置,显式声明模块搜索根路径:
    [pytest]
    pythonpath = .
    testpaths = tests
    
  • 方案3:配置VSCode启动环境变量
    在项目根目录下新建.vscode/launch.json文件,写入启动配置,将项目根目录加入PYTHONPATH环境变量:
    {
      "version": "0.2.0",
      "configurations": [
        {
          "name": "Python: 运行当前文件",
          "type": "python",
          "request": "launch",
          "program": "${file}",
          "console": "integratedTerminal",
          "env": {
            "PYTHONPATH": "${workspaceFolder}"
          }
        }
      ]
    }
    

内容的提问来源于stack exchange,提问作者Atilio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 18:24:31