包装 Python 项目¶
This tutorial walks you through how to package a simple Python project. It will show you how to add the necessary files and structure to create the package, how to build the package, and how to upload it to the Python Package Index (PyPI).
小技巧
如果你在运行本教程中的命令时遇到困难,请复制命令及其输出,然后在 GitHub 上的 packaging-problems 仓库中 open an issue。我们会尽力帮助你!
一些命令需要较新版本的 pip,所以首先要确保你安装了最新的版本:
python3 -m pip install --upgrade pip
py -m pip install --upgrade pip
一个简单的项目¶
This tutorial uses a simple project named
example_package_YOUR_USERNAME_HERE
. If your username is me
, then the
package would be example_package_me
; this ensures that you have a unique
package name that doesn’t conflict with packages uploaded by other people
following this tutorial. We recommend following this tutorial as-is using this
project, before packaging your own project.
在本地创建以下文件结构:
packaging_tutorial/
└── src/
└── example_package_YOUR_USERNAME_HERE/
├── __init__.py
└── example.py
The directory containing the Python files should match the project name. This simplifies the configuration and is more obvious to users who install the package.
__init__.py
是导入目录作为一个包所需要的,应该是空的。
example.py
是包内模块的一个例子,可以包含你的包的逻辑(函数、类、常量等等)。打开该文件并输入以下内容:
def add_one(number):
return number + 1
如果你不熟悉 Python 的 modules 和 import packages,请花几分钟时间阅读一下 Python 软件包和模块的文档。
一旦你创建了这个结构,你就想在 packaging_tutorial
目录下运行本教程中的所有命令。
创建包文件¶
你现在将添加用于准备项目发布的文件。当你完成后,项目结构将看起来像这样:
packaging_tutorial/
├── LICENSE
├── pyproject.toml
├── README.md
├── src/
│ └── example_package_YOUR_USERNAME_HERE/
│ ├── __init__.py
│ └── example.py
└── tests/
创建测试目录¶
tests/
是一个测试文件的占位符。现在让它为空。
创建 pyproject.toml¶
pyproject.toml
tells “frontend” build tools like pip and
build what “backend” tool to use to create
distribution packages for your project.
You can choose from a number of backends; this tutorial uses Hatchling by default, but it will work identically with setuptools,
Flit, PDM, and others that support the [project]
table for metadata.
备注
Some build backends are part of larger tools that provide a command-line interface with additional features like project initialization and version management, as well as building, uploading, and installing packages. This tutorial uses single-purpose tools that work independently.
Open pyproject.toml
and enter one of these [build-system]
tables:
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[build-system]
requires = ["flit_core>=3.4"]
build-backend = "flit_core.buildapi"
[build-system]
requires = ["pdm-pep517"]
build-backend = "pdm.pep517.api"
requires
is a list of packages that are needed to build your package. You don’t need to install them; build frontends like pip will install them automatically in a temporary, isolated virtual environment for use during the build process.build-backend
is the name of the Python object that frontends will use to perform the build.
配置元数据¶
Open pyproject.toml
and enter the following content. Change the name
to include your username; this ensures that you have a unique
package name that doesn’t conflict with packages uploaded by other people
following this tutorial.
[project]
name = "example_package_YOUR_USERNAME_HERE"
version = "0.0.1"
authors = [
{ name="Example Author", email="author@example.com" },
]
description = "A small example package"
readme = "README.md"
requires-python = ">=3.7"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
[project.urls]
"Homepage" = "https://github.com/pypa/sampleproject"
"Bug Tracker" = "https://github.com/pypa/sampleproject/issues"
name
is the distribution name of your package. This can be any name as long as it only contains letters, numbers,.
,_
, and-
. It also must not already be taken on PyPI. Be sure to update this with your username for this tutorial, as this ensures you won’t try to upload a package with the same name as one which already exists.version
is the package version. See the version specifier specification for more details on versions. Some build backends allow it to be specified another way, such as from a file or a git tag.authors
is used to identify the author of the package; you specify a name and an email for each author. You can also listmaintainers
in the same format.description
is a short, one-sentence summary of the package.readme
is a path to a file containing a detailed description of the package. This is shown on the package detail page on PyPI. In this case, the description is loaded fromREADME.md
(which is a common pattern). There also is a more advanced table form described in the project metadata specification.requires-python
gives the versions of Python supported by your project. Installers like pip will look back through older versions of packages until it finds one that has a matching Python version.classifiers
gives the index and pip some additional metadata about your package. In this case, the package is only compatible with Python 3, is licensed under the MIT license, and is OS-independent. You should always include at least which version(s) of Python your package works on, which license your package is available under, and which operating systems your package will work on. For a complete list of classifiers, see https://pypi.org/classifiers/.urls
lets you list any number of extra links to show on PyPI. Generally this could be to the source, documentation, issue trackers, etc.
See the project metadata specification for
details on these and other fields that can be defined in the [project]
table. Other common fields are keywords
to improve discoverability and the
dependencies
that are required to install your package.
创建 README.md¶
打开 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.
Creating a LICENSE¶
It’s important for every package uploaded to the Python Package Index to include
a license. This tells users who install your package the terms under which they
can use your package. For help picking a license, see
https://choosealicense.com/. Once you have chosen a license, open
LICENSE
and enter the license text. For example, if you had chosen the
MIT license:
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.
Most build backends automatically include license files in packages. See your backend’s documentation for more details.
包括其他文件¶
The files listed above will be included automatically in your source distribution. If you want to include additional files, see the documentation for your build backend.
生成分发档案¶
下一步是为该软件包生成 distribution packages。这些是上传到 Python 包索引的档案,可以通过 pip 来安装。
确保您安装了最新版本的 PyPA 的 build:
python3 -m pip install --upgrade build
py -m pip install --upgrade build
小技巧
如果您在安装这些东西时遇到困难,请查看 安装包 教程。
现在从 pyproject.toml
所在的同一目录运行此命令:
python3 -m build
py -m build
这个命令应该输出大量的文本,一旦完成应该在 dist
目录下产生两个文件:
dist/
├── example_package_YOUR_USERNAME_HERE-0.0.1-py3-none-any.whl
└── example_package_YOUR_USERNAME_HERE-0.0.1.tar.gz
The tar.gz
file is a source distribution
whereas the .whl
file is a built distribution.
Newer pip versions preferentially install built distributions, but will
fall back to source distributions if needed. You should always upload a source
distribution and provide built distributions for the platforms your project is
compatible with. In this case, our example package is compatible with Python on
any platform so only one built distribution is needed.
上传分发档案¶
最后,是时候把您的软件包上传到 Python Package Index 了!
The first thing you’ll need to do is register an account on TestPyPI, which is a separate instance of the package index intended for testing and experimentation. It’s great for things like this tutorial where we don’t necessarily want to upload to the real index. To register an account, go to https://test.pypi.org/account/register/ and complete the steps on that page. You will also need to verify your email address before you’re able to upload any packages. For more details, see 使用 TestPyPI.
To securely upload your project, you’ll need a PyPI API token. Create one at https://test.pypi.org/manage/account/#api-tokens, setting the “Scope” to “Entire account”. Don’t close the page until you have copied and saved the token — you won’t see that token again.
现在您已经注册了,您可以使用 twine 来上传发行包。您需要安装 Twine:
python3 -m pip install --upgrade twine
py -m pip install --upgrade twine
安装完毕后,运行 Twine 以上传 dist
下的所有档案:
python3 -m twine upload --repository testpypi dist/*
py -m twine upload --repository testpypi dist/*
You will be prompted for a username and password. For the username,
use __token__
. For the password, use the token value, including
the pypi-
prefix.
命令完成后,您应该会看到类似这样的输出:
Uploading distributions to https://test.pypi.org/legacy/
Enter your username: __token__
Uploading example_package_YOUR_USERNAME_HERE-0.0.1-py3-none-any.whl
100% ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 8.2/8.2 kB • 00:01 • ?
Uploading example_package_YOUR_USERNAME_HERE-0.0.1.tar.gz
100% ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 6.8/6.8 kB • 00:00 • ?
Once uploaded, your package should be viewable on TestPyPI; for example:
https://test.pypi.org/project/example_package_YOUR_USERNAME_HERE
.
安装您新上传的软件包¶
You can use pip to install your package and verify that it works. Create a virtual environment and install your package from TestPyPI:
python3 -m pip install --index-url https://test.pypi.org/simple/ --no-deps example-package-YOUR-USERNAME-HERE
py -m pip install --index-url https://test.pypi.org/simple/ --no-deps example-package-YOUR-USERNAME-HERE
请确保在软件包名称中指定您的用户名!
pip应该会安装 TestPyPI 的软件包,输出结果应该是这样的:
Collecting example-package-YOUR-USERNAME-HERE
Downloading https://test-files.pythonhosted.org/packages/.../example_package_YOUR_USERNAME_HERE_0.0.1-py3-none-any.whl
Installing collected packages: example_package_YOUR_USERNAME_HERE
Successfully installed example_package_YOUR_USERNAME_HERE-0.0.1
备注
This example uses --index-url
flag to specify TestPyPI instead of
live PyPI. Additionally, it specifies --no-deps
. Since TestPyPI doesn’t
have the same packages as the live PyPI, it’s possible that attempting to
install dependencies may fail or install something unexpected. While our
example package doesn’t have any dependencies, it’s a good practice to avoid
installing dependencies when using TestPyPI.
You can test that it was installed correctly by importing the package. Make sure you’re still in your virtual environment, then run Python:
python3
py
并导入该软件包:
>>> from example_package_YOUR_USERNAME_HERE import example
>>> example.add_one(2)
3
下一步¶
Congratulations, you’ve packaged and distributed a Python project! ✨ 🍰 ✨
Keep in mind that this tutorial showed you how to upload your package to Test PyPI, which isn’t a permanent storage. The Test system occasionally deletes packages and accounts. It is best to use TestPyPI for testing and experiments like this tutorial.
When you are ready to upload a real package to the Python Package Index you can do much the same as you did in this tutorial, but with these important differences:
Choose a memorable and unique name for your package. You don’t have to append your username as you did in the tutorial, but you can’t use an existing name.
Register an account on https://pypi.org - note that these are two separate servers and the login details from the test server are not shared with the main server.
Use
twine upload dist/*
to upload your package and enter your credentials for the account you registered on the real PyPI. Now that you’re uploading the package in production, you don’t need to specify--repository
; the package will upload to https://pypi.org/ by default.Install your package from the real PyPI using
python3 -m pip install [your-package]
.
At this point if you want to read more on packaging Python libraries here are some things you can do: