python -m build 为 Python 项目生成源码包(.tar.gz)和 Wheel 包(.whl),用于发布到 PyPI 或分发安装。
前置要求
1
2
3
4
| # 安装 build 工具
pip install build
# 项目需有 pyproject.toml
|
基本用法
1
2
3
4
5
6
7
8
| # 构建两种包
python -m build
# 仅构建 Wheel
python -m build --wheel
# 仅构建源码包
python -m build --sdist
|
构建结果存放在 dist/ 目录:
my_project-0.1.0.tar.gz(源码包)my_project-0.1.0-py3-none-any.whl(Wheel 包)
pyproject.toml 示例
1
2
3
4
5
6
7
8
| [build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "my_project"
version = "0.1.0"
dependencies = ["requests>=2.25.0"]
|
发布到 PyPI
1
2
| pip install twine
twine upload dist/*
|
本地安装测试
1
| pip install dist/my_project-0.1.0-py3-none-any.whl
|
常见问题
| 问题 | 解决 |
|---|
| 缺少 pyproject.toml | 创建配置文件,配置 [build-system] |
| 构建工具未安装 | pip install setuptools wheel |
| 源文件缺失 | 检查 MANIFEST.in 或自动包含规则 |
Comments