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

Python项目运行pytest时出现ModuleNotFoundError,模块导入失败怎么解决?

解决Python pytest测试文件导入src模块的ModuleNotFoundError问题

针对你遇到的测试文件无法导入src目录模块的问题,以下是几种实用的解决办法:

方法1:将src目录转为可导入的Python包

  • 在src目录下创建空的__init__.py文件,让Python识别src为合法的包目录。
  • 修改tests_logic.py中的导入语句,改为基于项目根目录(main_folder)的绝对导入:
    from src.main import something
    from src.logic import something
    
  • 运行测试时,必须在main_folder目录下执行命令:
    pytest test/tests_logic.py
    
    此时Python会自动把当前目录(main_folder)加入模块搜索路径,就能正常找到src包。

方法2:手动将src目录加入Python路径

如果不想修改项目结构,可以在测试文件开头添加代码,临时把src目录加入模块搜索路径:

import sys
from pathlib import Path

# 定位到main_folder目录
test_dir = Path(__file__).parent
main_folder = test_dir.parent
src_path = main_folder / "src"

# 将src路径加入sys.path
sys.path.append(str(src_path))

# 现在可以直接导入src下的模块
from main import something
from logic import something

方法3:用pytest的conftest.py统一配置路径

在test目录下创建conftest.py文件,写入以下代码,所有测试文件运行时都会自动加载这个配置:

import sys
from pathlib import Path

# 把src目录加入模块搜索路径
main_folder = Path(__file__).parent.parent
sys.path.append(str(main_folder / "src"))

之后测试文件里直接用from main import something这类语句即可,无需每个文件都加路径配置。

关键注意事项

  • 你之前用的from main_file.src.main import ...是错误的,项目根目录是main_folder,不存在main_file这个包,要根据实际目录结构调整导入路径。
  • 避免在子目录下直接运行测试命令,路径混乱很容易导致模块找不到的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 12:14:57