hatch env run 不能直接跑多版本测试,因为它默认只作用于当前活动环境(通常是 default),不自动遍历 python 版本;矩阵测试需用 hatch matrix,通过 matrix 和 matrix-values 在 hatch.toml 中定义多版本组合,并由 hatch matrix test 执行。

为什么 hatch env run 不能直接跑多版本测试
因为 hatch env run 默认只作用于当前活动环境(通常是 default),它不自动遍历 Python 版本。所谓“矩阵测试”,本质是为每个 python = ["3.9", "3.10", "3.11"] 创建独立环境并执行相同命令——这得靠 hatch matrix,不是 run。
常见错误是写成 hatch env run --python 3.9,3.10 test,结果报错 Unknown option '--python':这个参数只在 hatch run 或 hatch matrix 中合法,且语义不同。
-
hatch run:在当前项目环境里执行命令(不切换 Python 版本) -
hatch matrix:按配置生成多个环境,每个环境用指定 Python 版本安装依赖并运行
如何用 hatch.toml 定义矩阵维度
关键不是写死所有组合,而是把可变部分抽象成变量。比如你想测不同 Python 版本 + 不同 pytest 版本,就用 [tool.hatch.envs.test] 配置:
[tool.hatch.envs.test]
matrix = [
["python", "pytest"],
]
matrix-values = {
python = ["3.9", "3.10", "3.11"],
pytest = ["7.4", "8.2"],
}
dependencies = ["pytest=={pytest}"]
commands = ["pytest tests/"]
注意:matrix-values 是字典,键名必须和 matrix 子数组里的字符串完全一致;{pytest} 这种插值只在 dependencies 和 commands 中生效,不能用在 python 字段里(Python 版本由 matrix 第一项控制)。
- 如果只测 Python 版本,
matrix = [["python"]]就够了 - 想跳过某个组合(如
py3.9 + pytest8.2),加skip = ["3.9-8.2"]到该 env 下 -
python字段值必须是字符串,不能写3.9(没引号会解析失败)
运行时怎么看到每个环境实际用了什么版本
hatch matrix test 默认静默执行,出错才打印日志。要确认每个子环境的 Python 和依赖版本,得加 --verbose 或提前用 --dry-run:
hatch matrix test --dry-run
输出类似:
test.py3.9-pytest7.4: python=3.9, dependencies=["pytest==7.4"] test.py3.9-pytest8.2: python=3.9, dependencies=["pytest==8.2"] test.py3.10-pytest7.4: python=3.10, dependencies=["pytest==7.4"] ...
真实运行时,每个环境会单独打印自己的 python --version 和 pip list | grep pytest 结果——但前提是你的 commands 里显式写了这些检查。否则光看 pytest 输出,根本分不清它跑在哪个 Python 上。
- 建议在
commands开头加python -c "import sys; print(sys.version)" - 避免用
which python,它可能返回 Hatch 的 wrapper 路径,看不出真实版本 - Windows 用户注意:
cmd不支持"嵌套,改用python -c "import sys; print(sys.version)"即可(Hatch 会自动处理引号)
CI 中跑矩阵测试容易漏掉的兼容性陷阱
本地 hatch matrix 成功,不等于 CI 也稳。最常被忽略的是 build-backend 和 requires 兼容性:Hatch 自己要用 Python 3.8+ 构建项目,但你测试的 py3.7 环境可能连 pyproject.toml 都解析不了。
例如,如果你的 pyproject.toml 用了 hatchling 1.20.0+(要求 Python ≥3.8),那 python = ["3.7"] 的矩阵项会在安装构建依赖阶段直接失败,错误信息是 UnsupportedPythonError 或 No module named 'tomllib'(3.7 缺少标准库模块)。
- 查清你用的
hatchling最低支持 Python 版本,再决定矩阵是否包含老旧版本 - 若必须支持 py3.7,降级
hatchling到 1.15.x,并在[build-system]中锁定requires = ["hatchling - GitHub Actions 中用
setup-python安装旧版 Python 时,注意某些 Ubuntu runner 默认不带 py3.7,得手动加python-version: '3.7'并确认镜像支持
矩阵测试真正的难点不在写法,而在于每个环境都是隔离的黑盒——你得主动暴露它的 Python、构建工具链、依赖版本,否则失败时连问题出在哪一层都难定位。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











