0%

打包流程

The Packaging Flow

Publishing a package requires a flow from the author’s source code to an end user’s Python environment.

  1. 拥有包含该包的 source tree。这通常是从版本控制系统 (VCS) 检出的。
  2. 准备一个配置文件用来描述 package 的元数据(name、version…)并且指定如何创建 build artifacts,对于大多数包而言,这个配置文件通常是 pyproject.toml,在 source tree 中手动维护。
  3. 创建要发布到包分发服务 PyPI 的构建产物,这些产物通常是 source distribution sdist 和 wheels。这些构建产物是由构建工具根据配置文件构建出来的。
  4. 上传构建产物到包分发服务 package distribution service。
  5. 从 PyPI 下载包。
  6. 安装到自己的 Python 环境,这一步通常会涉及 build/compile 步骤,如果需要必须由包的元数据描述如何构建。

Source tree

The source tree contains the package source code, usually a checkout from a VCS. The particular version of the code used to create the build artifacts will typically be a checkout based on a tag associated with the version.

The configuration file

配置文件依赖于构建产物的构建工具,不同的构建工具使用不同的配置文件,标准实践使用 pyproject.toml

pyproject.toml 文件至少需要一个指定构建工具的 [build-system] 元素。有许多构建工具包括不限于 flithatchpdmpoetrysetuptools等,每个工具的文档都给出了在 [build-system] 中填写的内容。

1
2
3
[build-system]
require = ["hatchling"]
build-backend = "hatchling.build"

有了这个配置,前端构建工具(比如 build)会调用指定的 build-backend 来构建项目,不同的构建工具可能会有自己的前端。像 pip 这样的安装工具在运行构建工具的后端以从源发行版进行安装时也充当前端。

不同的构建后端工具可能需要不同的配置信息。

Build artifacts

The source distribution sdist

源代码发行版包含足够的内容,可以在最终用户的 Python 环境中从源代码安装软件包。As such 因此, it needs the package source, and may also include tests and documentation. 这些对于想要开发源代码的最终用户以及需要某些本地编译步骤的最终用户系统非常有用。

build 工具知道如何调用你指定的构建后端工具来构建产物 python3 -m build --sdist source-tree-directory

The built distributions wheels

A built distribution contains only the files needed for an end user’s Python environment. 安装过程中不需要编译步骤,并且 wheel 文件能简单的解压缩到 site-packages 目录。这样会让安装过程非常快,并且对用户很方便。

一个纯 Python 包通常只需要一个 generic wheel。 A package with compiled binary extensions needs a wheel for each supported combination of Python interpreter, operating system, and CPU architecture that it supports. 如果有用 C 语言编写的扩展,需要构建若干个版本来支持不同的解释器、操作系统、CPU 架构。具有已编译二进制扩展的包需要一个轮子来支持它所支持的 Python 解释器、操作系统和 CPU 架构的每个受支持组合。

如果没有合适的 wheel 文件,pip 等工具将回退到安装源发行版。

原来如此,恍然大悟,纯 python 编写的包可以用 tar.gz 和通用 wheel,如果有 C 扩展,需要为受支持的不同平台做不同的 wheel。

python3 -m build --wheel source-tree-directory

sdist = 源码包 ,wheel 可以理解为二进制包,虽然 python 代码不会编译为通常理解的二进制机器码,可以这样理解。

build 的默认行为是同时构建 sdist 和 wheel。

Upload to the package distribution service

twine upload dist/package-name-version.tar.gz dist/package-name-version-py3-none-any.whl 通常使用 twine。

Download and install

python3 -m pip install package-name。或者使用 pipenvpoetrypdm