跳转到主要内容

使用PEP 517钩子构建Python包的包装器

项目描述

PEP 517 为构建Python包的系统指定了一个标准API。

PEP 660 通过引入一个可编辑安装的构建模式对其进行扩展。

此包包含PEP 517和PEP 660指定的钩子的包装器。它提供

  • 在子进程中调用钩子的机制,以便它们与当前进程隔离。

  • 可选钩子的回退,以便前端可以在不检查哪些已定义的情况下调用钩子。

使用 pytesttox 运行测试。

使用说明——您负责确保构建需求可用

import os
import tomli
from pep517.wrappers import Pep517HookCaller

src = 'path/to/source'  # Folder containing 'pyproject.toml'
with open(os.path.join(src, 'pyproject.toml'), 'rb') as f:
    build_sys = tomli.load(f)['build-system']

print(build_sys['requires'])  # List of static requirements
# The caller is responsible for installing these and running the hooks in
# an environment where they are available.

hooks = Pep517HookCaller(
    src,
    build_backend=build_sys['build-backend'],
    backend_path=build_sys.get('backend-path'),
)

config_options = {}   # Optional parameters for backend
# List of dynamic requirements:
print(hooks.get_requires_for_build_wheel(config_options))
# Again, the caller is responsible for installing these build requirements

destination = 'also/a/folder'
whl_filename = hooks.build_wheel(destination, config_options)
assert os.path.isfile(os.path.join(destination, whl_filename))

已弃用的高级

目前,pep517 也包含了一些高级功能,这些功能将构建依赖项安装到临时环境中,并使用它们构建 wheel/sdist。这是一个粗略的实现,例如它没有进行适当的构建隔离。《PyPA build 项目》被推荐作为替代方案,尽管它在2020年10月仍然相当年轻。现在,pep517 中的这一层功能已被弃用,但由于有代码依赖于它,所以不会在短时间内移除。

高级用法,处理构建需求

import os
from pep517.envbuild import build_wheel, build_sdist

src = 'path/to/source'  # Folder containing 'pyproject.toml'
destination = 'also/a/folder'
whl_filename = build_wheel(src, destination)
assert os.path.isfile(os.path.join(destination, whl_filename))

targz_filename = build_sdist(src, destination)
assert os.path.isfile(os.path.join(destination, targz_filename))

要测试项目的构建后端,请在系统外壳中运行

python3 -m pep517.check path/to/source  # source dir containing pyproject.toml

要构建后端到源和/或二进制分发,请在外壳中运行

python -m pep517.build path/to/source  # source dir containing pyproject.toml

所有这些高级功能都已弃用。

由以下组织支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面