1.现代打包方式(pyproject.toml)
当前主流方案
替代 setup.py
支持构建隔离、标准化元数据
1.1项目结构
1 2 3 4 5 6 7 8 9 10
| myproject/ ├── src/ │ └── myproject/ │ ├── __init__.py │ ├── core.py │ └── cli.py ├── tests/ ├── README.md ├── pyproject.toml └── LICENSE
|
⚠️ 强烈建议用 src/ 布局(避免本地路径污染)
1.2核心配置:pyproject.toml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| [build-system] requires = ["setuptools>=61.0", "wheel"] build-backend = "setuptools.build_meta"
[project] name = "myproject" version = "0.1.0" description = "A production-grade Python package" readme = "README.md" authors = [ { name = "GaGa", email = "gaga@example.com" } ] license = { text = "MIT" } requires-python = ">=3.8"
dependencies = [ "requests>=2.28.0", ]
[project.scripts] mycli = "myproject.cli:main"
classifiers = [ "Programming Language :: Python :: 3", "Operating System :: OS Independent", ]
[tool.setuptools] package-dir = {"" = "src"}
[tool.setuptools.packages.find] where = ["src"]
|
2.构建流程(标准化)
2.1安装构建工具
2.2构建包
生成:
1 2 3
| dist/ ├── myproject-0.1.0.tar.gz └── myproject-0.1.0-py3-none-any.whl
|
2.3本地安装测试
3.发布到 PyPI
3.1安装上传工具
3.2上传
4.关键机制解析
4.1 构建流程(PEP 517)
graph TD
A[pyproject.toml] --> B[build backend setuptools]
B --> C[sdist tar.gz]
B --> D[wheel .whl]
C --> E[pip install]
D --> E
4.2 wheel vs sdist
| 类型 |
特点 |
使用场景 |
| sdist |
源码包 |
可移植,需构建 |
| wheel |
二进制包 |
安装快,生产推荐 |