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

如何修改Python导入语句并解决单元测试的模块路径问题?

问题描述

在包含src/(存放square.py)和test/(存放test_square.py)的Python项目中,遇到以下模块导入问题:

  • 测试文件使用from src.square import Square时,进入test/目录执行python -m unittest test_square,会报错ModuleNotFoundError: No module named 'src'
  • 在项目根目录执行python -m unittest test/test_square.py,会报错ModuleNotFoundError: No module named 'test.test_square'

希望找到**无需修改PYTHONPATH或在代码中操作sys.path**的优雅解决方案,同时能将导入语句改为from square import Square。

解决方案

方案1:将src目录转为可安装的包(推荐最佳实践)

这是Python项目的标准规范,既能彻底解决导入问题,也符合包分发的最佳实践:

  1. 在项目根目录创建pyproject.toml文件,内容如下:
    [build-system]
    requires = ["setuptools>=61.0"]
    build-backend = "setuptools.build_meta"
    
    [project]
    name = "square-library"
    version = "0.1.0"
    packages = ["square"]
    package_dir = {"square": "src"}
    
    注:如果src/下直接是square.py而非子目录,可将配置改为:packages = [""]、package_dir = {"": "src"}
  2. 在根目录执行开发模式安装命令:
    pip install -e .
    
    此命令会将src目录以链接形式加入Python的包搜索路径,之后无论在项目哪个目录,都可以直接使用from square import Square,执行unittest命令也不会再出现模块找不到的问题。

方案2:调整测试目录结构+使用unittest测试发现

无需安装包,仅通过目录调整和标准命令解决问题:

  1. 在test/目录下创建空的__init__.py文件,将test目录转为Python包
  2. 在项目根目录执行unittest的测试发现命令:
    python -m unittest discover
    
    此时Python会自动将根目录加入包搜索路径,测试文件中可使用from src.square import Square;若要改为from square import Square,需在src/目录下也创建空的__init__.py,并临时将src加入Python路径(如Linux/macOS执行export PYTHONPATH=./src,Windows执行set PYTHONPATH=./src),但这种方式不如方案1优雅。

方案3:使用pytest替代unittest(更简洁的测试工具)

如果允许更换测试框架,pytest的自动路径处理更友好:

  1. 安装pytest:
    pip install pytest
    
  2. 在项目根目录创建pytest.ini文件,指定Python路径:
    [pytest]
    pythonpath = src
    
  3. 在根目录执行pytest命令,pytest会自动识别测试文件,且测试文件中可直接使用from square import Square。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:25:56