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

PyCharm中pytest测试正常,命令行运行遇模块导入错误求助

问题:PyCharm中pytest测试正常,命令行运行出现模块导入错误

场景描述

在PyCharm中运行pytest测试套件时所有测试均成功,但通过命令行运行时出现模块导入错误。

项目配置与代码信息

pytest.ini 配置

[pytest]
minversion = 7.0
addopts = --cov --cov-report=html:converter_coverage
pythonpath = src/converter
testpaths = 
 tests

测试样例代码

from converter.question_parser import readSingleFile, getAllQuestionsFromFiles

def test_ifTheLanguageIsDutch_andValidTextInputIsGiven_ThenAQuestionIsMade():   
    foundQuestions = readSingleFile("tests/resources/SingleMinimalQuestion_NL.txt", "NL")
    assert len(foundQuestions) == 1
    
    question = foundQuestions[0]
    assert question.longQuestion == "This is the long question?"
    assert question.shortQuestion == "This is the short question?"
    assert question.answer == "This is the answer"
    assert question.category == "This is the category"
    assert question.round == "This is the round"

命令行报错信息

_________________________________________________________________ ERROR collecting tests/test_question_parser.py __________________________________________________________________ 
ImportError while importing test module 'C:\Users\peter\Projects\kwismaster\converter\tests\test_question_parser.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
..\..\..\..\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py:90: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
test_question_parser.py:1: in <module>
    from converter.question_parser import readSingleFile, getAllQuestionsFromFiles
E   ModuleNotFoundError: No module named 'converter'

已尝试的方案

  • 调整pytest.ini中的路径配置,无效果
  • 修改导入语句为from src.converter.question_parser import ...,并设置pythonpath = . src src/converter,命令行测试可运行,但PyCharm中的代码跳转导航功能失效

需求

寻求兼容命令行与PyCharm运行,同时保留PyCharm代码跳转导航功能的解决方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 19:02:39