Skip to content

Python 包构建与 PyPI 自动化发布指南

归类:Python / 包管理与发布 发生时间:2026-07-13 状态:✅ 已解决


一、 问题现象 / 背景

在 79team 孵化出团队级别的 Python 工具包(如 opc-agentflow)后,为了实现团队级别的复用、分发和依赖管理,需要将其打包并托管到公共包管理平台 PyPI (https://pypi.org) 或团队的私有镜像源上。

二、 根本原因 / 设计思路

现代化 Python 打包遵循 PEP 517 / PEP 518 规范,淘汰了传统的 setup.py 直接执行方式,转而采用声明式的 pyproject.toml 配置。

  • 构建后端 (Build Backend):使用 setuptoolshatchling,负责将源码打包为标准分发格式。
  • 构建前端 (Build Frontend):使用 build 模块,调起构建后端生成源码包(.tar.gz)和二进制轮子(.whl)。
  • 上传工具 (Upload Tool):使用 twine 进行网络安全上传,利用专属 API Token 防止账户密码泄露。

三、 解决方案 / 推荐做法

步骤 1:配置 pyproject.toml

在项目根目录创建或完善 pyproject.toml,确保包含元数据和构建后端定义:

toml
[build-system]
requires = ["setuptools>=61.0.0", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "opc-agentflow"
version = "0.1.0"
description = "79team 运维与实施控制 (OPC) 声明式任务流引擎与安全网闸"
readme = "README.md"
requires-python = ">=3.11"
authors = [
    { name = "79team R&D", email = "rd@79online.com" }
]
classifiers = [
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: MIT License",
]
dependencies = [
    "psutil>=5.9.0",
    "pyyaml>=6.0.1",
]

[tool.setuptools.packages.find]
where = ["."]
include = ["opc_agentflow*"]

步骤 2:生成 PyPI API Token

  1. 登录 PyPI 账户,启用双因素认证 (2FA)。
  2. 导航至 Account Settings -> API tokens
  3. 点击 Add API token,选择 Scope(第一次发布新包时,设为整个账户 "Entire account",发布后再设为针对具体包的限制 scope)。
  4. 复制生成的 API Token(前缀为 pypi-)。注意:关闭页面后将无法再次查看该 Token

步骤 3:本地打包构建

在项目根目录下安装构建工具,并执行打包:

bash
# 安装最新版构建工具和上传工具
python3 -m pip install --upgrade build twine

# 清理历史构建产物(如 dist/ 目录已存在)
rm -rf dist/ build/ *.egg-info

# 触发本地构建
python3 -m build

构建成功后,会在 dist/ 目录下生成两个文件:

  • opc-agentflow-0.1.0.tar.gz (源码包)
  • opc_agentflow-0.1.0-py3-none-any.whl (二进制分发轮子)

步骤 4:上传到 PyPI

使用 twine 安全地上传包:

bash
# 验证打包产物合规性
python3 -m twine check dist/*

# 上传到 PyPI (生产环境)
python3 -m twine upload dist/*
  • 提示输入 Username 时:输入字面量 __token__
  • 提示输入 Password 时:粘贴此前在 PyPI 生成的 API Token(包含 pypi- 前缀)。

如果需要上传到测试环境进行试运行,可以使用 TestPyPI:

bash
python3 -m twine upload --repository testpypi dist/*

四、 本地高效发布替代方案 (使用 uv)

如果本地环境已安装现代 Python 依赖管理工具 uv,发布流程可以极速缩短为:

bash
# 构建项目
uv build

# 上传发布
uv publish --token pypi-YOUR_API_TOKEN_HERE

五、 GitHub Actions 自动化 CI 发布建议 (无密钥校验)

为避免在 CI 环境暴露 API Token,建议在 GitHub 仓库中配置 PyPI Trusted Publishers (受信任发布者)

  1. 在 PyPI 项目管理后台中,在 "Trusted Publishers" 栏目添加你的 GitHub 仓库路径、Workflow 名字及 Environment。
  2. .github/workflows/publish.yml 中使用官方发布动作,无需任何 Token 密钥:
yaml
name: Publish to PyPI

on:
  release:
    types: [published]

permissions:
  id-token: write  # OIDC 身份认证必需

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.11"
      - name: Build dist
        run: |
          pip install build
          python -m build
      - name: Publish package
        uses: pypa/gh-action-pypi-publish@release/v1