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

Python虚拟环境运行pytest抛出ModuleNotFoundError问题求助

问题:虚拟环境下pytest无法导入已安装的第三方模块

初始环境

  • 使用全局安装的Python 3.9.13开发,未启用虚拟环境
  • 项目结构:
mypkg/
   sub_mypkg/
      file_a.py
      pytest.ini
      testing/
         __init__.py
         test_a.py    
  • file_a.py中导入了pandas等第三方模块,test_a.py的测试用例会调用file_a.py中的代码
  • pytest.ini已配置将项目根目录添加至PYTHONPATH,此环境下pytest运行完全正常

问题复现

  • 为项目创建Python 3.11版本的虚拟环境,安装了所有必要模块(包括pytest),并卸载了全局pytest
  • 激活虚拟环境后运行pytest,直接抛出ModuleNotFoundError: No module named 'pandas'

虚拟环境已安装的模块清单:

Package         Version
--------------- -------
attrs           22.1.0
colorama        0.4.6
contourpy       1.0.6
cycler          0.11.0
et-xmlfile      1.1.0
exceptiongroup  1.0.4
fonttools       4.38.0
iniconfig       1.1.1
kiwisolver      1.4.4
matplotlib      3.6.2
numpy           1.23.4
openpyxl        3.0.10
packaging       21.3
pandas          1.5.1
Pillow          9.3.0
pip             22.3.1
pluggy          1.0.0
pyparsing       3.0.9
pytest          7.2.0
python-dateutil 2.8.2
pytz            2022.6
PyYAML          6.0
setuptools      56.0.0
six             1.16.0
tomli           2.0.1

已做的排查与尝试

  • 确认虚拟环境中pandas已正确安装:可在REPL中正常导入,逐行运行test_a.py的代码也无报错
  • 替换导入模块验证:将file_a.py中的import pandas改为import numpy,运行pytest时同样抛出ModuleNotFoundError,说明问题并非特定模块导致
  • 测试不同Python版本的虚拟环境:仅Python 3.9.13的虚拟环境中pytest能正常运行,尝试3.11.0、3.10.7、3.9.6版本均出现相同的模块找不到问题
  • 其他尝试:添加/删除各目录下的__init__.py、更换pytest版本(6.2.5、7.0.0)、确认sys.path已包含项目根目录,但问题仍未解决

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:25:17