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

如何让Python脚本在正常执行与pytest测试下均正确运行?

解决pytest与脚本运行的模块导入冲突问题

方案一:将src作为可编辑包安装(推荐)

这是最规范的长期解决方案,适配所有运行场景:

  1. 在项目根目录(与src、tests同级)创建pyproject.toml文件,写入以下内容:
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "your-project"
version = "0.1.0"
packages = ["src"]
  1. 在根目录执行命令安装可编辑包:
pip install -e .
  1. 修改main.py中的导入语句为:
from src.util import UTIL_VALUE

此时无论是执行python src/main.py还是pytest tests/,模块导入都能正常工作。

方案二:动态调整Python路径(快速临时方案)

如果不想配置包结构,可通过以下方式临时修复路径问题:

方式1:在测试文件中添加根目录路径

修改tests/test_main.py的开头代码:

import sys
import os
# 将项目根目录添加到Python搜索路径
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

# 之后正常导入src下的模块
from src.main import ...

方式2:运行pytest时设置环境变量

在项目根目录执行pytest前,先指定PYTHONPATH:

# Linux/macOS
PYTHONPATH=. pytest tests/

# Windows(PowerShell)
$env:PYTHONPATH="."; pytest tests/

这种方式下main.py可以保留from util import UTIL_VALUE,无需修改。

方案三:让main.py兼容两种导入逻辑

修改main.py的开头代码,根据运行场景自动调整路径:

import sys
import os

# 获取当前脚本所在的src目录路径
src_dir = os.path.dirname(os.path.abspath(__file__))
# 将src目录加入Python搜索路径的最前面
if src_dir not in sys.path:
    sys.path.insert(0, src_dir)

from util import UTIL_VALUE

同时在tests/test_main.py中使用from src.util import UTIL_VALUE,即可同时满足脚本运行和pytest测试的导入需求。

内容的提问来源于stack exchange,提问作者j-carrara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:52:20