构建与发布 Python 包
项目结构
packaging_tutorial/
├── LICENSE
├── pyproject.toml
├── README.md
├── src/
│ └── sampleproject/
│ ├── __init__.py
│ └── example.py
└── tests/
src 下的包名是用户 import 你的包时使用的名字。
pyproject.toml
pyproject.toml 和 setup.py 都可用于配置项目,现代 Python 更推荐使用 pyproject.toml。下面是一个示例:
[project]
name = "sampleproject"
version = "0.0.1"
authors = [
{ name="Example Author", email="author@example.com" },
]
description = "A small example package"
readme = "README.md"
requires-python = ">=3.9"
classifiers = [
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
]
license = "MIT"
license-files = ["LICENSE"]
[project.urls]
Homepage = "https://github.com/pypa/sampleproject"
Issues = "https://github.com/pypa/sampleproject/issues"
project.name 是用户使用 pip 安装你的包时使用的名字。
example.py
def greeting():
print("Hello, world!")
README.md
# Example Package
This is a simple example package. You can use
[GitHub-flavored Markdown](https://guides.github.com/features/mastering-markdown/)
to write your content.
LICENSE
使用 MIT 协议:
Copyright (c) 2018 The Python Packaging Authority
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
构建包
-
安装依赖:
pip install build -
构建:
python -m build
构建产物会放置在 dist 目录下,其中有 .whl 和 .tar.gz 两种分发包。其中 .whl 是二进制分发,.tar.gz 是源码分发。Python 包至少要上传源码分发。
发布包
你可以在 TestPyPI 中注册账号并上传包。TestPyPI 是一个与 PyPI 类似,但专用于测试包发布的网站。
-
创建 API Token
-
编辑配置文件:
vim ~/.pypirc[testpypi] username = __token__ password = pypi-xxx -
安装依赖:
pip install twine -
上传包:
python -m twine upload --repository testpypi dist/*
安装包
-
安装:
pip install sampleproject --no-deps -i https://test.pypi.org/simple由于 TestPyPI 没有和 PyPI 相同的包,依赖解析可能会失败,因此需要使用
--no-deps选项。 -
测试:
>>> from sampleproject import example >>> example.greeting() Hello, world!
参考:Packaging Python Projects | Python Packaging User Guide
Troubleshooting
403 Forbidden
上传包时遇到如下错误:
ERROR HTTPError: 403 Forbidden from https://test.pypi.org/legacy/
Forbidden
原因:包名与其他包出现冲突。请修改 pyproject.toml 中的 project.name 项,重新构建分发包并上传。

浙公网安备 33010602011771号