确认Python构建环境是否就绪,需验证Agent上python3和pip是否可用、wheel是否已安装(≥0.40),Jenkins全局配置Python版本后仍需Pipeline中显式调用;推荐用python -m build替代setup.py bdist_wheel,确保pyproject.toml存在并清理缓存目录以保障构建一致性。

确认 Python 构建环境是否就绪
Jenkins 本身不自带 Python 环境,python 或 pip 命令能否执行,取决于 Jenkins Agent(或主节点)上是否已安装、路径是否在 PATH 中。常见错误是构建日志里直接报 command not found: python 或 ModuleNotFoundError: No module named 'wheel'。
- 登录 Jenkins Agent 机器,手动运行
which python3和python3 -m pip list | grep wheel,确认可执行且wheel已安装(>=0.40) - 若用 Docker agent,需在镜像中预装:例如
FROM python:3.11-slim+RUN pip install --upgrade pip wheel setuptools - Jenkins 全局工具配置中可注册多个 Python 版本,但 Pipeline 脚本里仍需显式调用,如
sh 'python3.11 -m build --wheel .'
用 build 替代老旧的 setup.py bdist_wheel
Python 官方自 2023 年起已弃用直接调用 setup.py 的方式,bdist_wheel 不再保证兼容性;现代标准是使用 build 工具(来自 build 包),它自动识别 pyproject.toml 配置并调用正确后端(如 setuptools 或 hatchling)。
- 确保项目根目录存在
pyproject.toml(哪怕只有最简内容:[build-system]+requires = ["hatchling"]) - 在 Jenkins Pipeline 中写:
sh 'python -m build --wheel --no-isolation .'(--no-isolation可跳过虚拟环境重建,提速且避免权限问题) - 输出默认在
dist/下,文件名形如myproject-0.1.0-py3-none-any.whl;注意build不会自动清理旧包,建议加sh 'rm -rf dist/ && python -m build --wheel .'
在 Pipeline 中安全提取并归档 .whl 文件
生成的 .whl 是交付核心产物,必须显式归档(archiveArtifacts),否则构建完成后即被丢弃。但直接写 dist/*.whl 有风险:若构建失败或未生成,Jenkins 会报错中断流程。
让 macOS 自动化像说话一样简单 —— 用代码控制你的 Mac,无需学习 AppleScript 系统要求 macOS 14+ (Sonoma) Python 3.9+ 需要开启:辅助功能 + 屏幕录制权限
- 先检查是否存在:
sh 'test -f dist/*.whl || { echo "No wheel file generated"; exit 1; }' - 再归档:
archiveArtifacts artifacts: 'dist/*.whl', fingerprint: true - 若需上传到私有仓库(如 Nexus、Artifactory),别用 shell 直连 curl —— 改用
nexus-jenkins-plugin或artifactory插件,它们支持凭证注入和重试逻辑 - 注意
dist/是工作区临时目录,不要在后续 stage 里假设它还存在;归档后如需复用,应unarchive或从artifacts显式拉取
避免因缓存或残留导致重复构建失败
Python 构建过程依赖 build 缓存(如 .build/)、__pycache__/、甚至 venv/,若 Jenkins workspace 复用且未清理,可能触发奇怪错误:比如 ImportError: cannot import name 'main' from 'pip'(pip 版本冲突)或元数据读取异常。
立即学习“Python免费学习笔记(深入)”;
- 推荐在 Pipeline 开头强制清理:
sh 'rm -rf .build __pycache__ *.egg-info venv/ .eggs/ dist/' - 禁用 Jenkins “保留最近 N 次构建” 的 workspace 复用(在 job 配置 → General → “Advanced Project Options” → 勾选 “Delete workspace before build starts”)
- 若用
pip install -e .测试本地安装,务必在独立子 shell 或虚拟环境中运行,避免污染全局 site-packages
真正麻烦的不是生成 .whl 这一步,而是构建上下文的一致性——Jenkins 的 workspace 生命周期、Python 的隐式缓存、以及 pyproject.toml 里未声明的构建后端依赖,三者叠加最容易在“本地能跑,Jenkins 报错”时卡住半天。

















