You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在setuptools的pyproject.toml中通过文件指定构建依赖?

Setuptools在pyproject.toml中配置外部构建依赖的正确方式

问题核心

build-system.requires是PEP 518规定的构建依赖字段,要求必须是字符串列表,不支持直接引用外部文件;同时[project].dynamic仅支持PEP 621枚举的项目元数据字段(如version、description),无法关联build-system.requires,这就是你之前配置报错的原因。

可行解决方案

方案1:通过脚本动态生成pyproject.toml

适合CI/CD或预构建场景,用脚本读取requirements-build.txt内容,自动填充到build-system.requires中:

示例Python脚本(命名为update_build_requires.py):

import tomli
import tomli_w

# 读取现有pyproject.toml
with open("pyproject.toml", "rb") as f:
    config = tomli.load(f)

# 读取构建依赖文件,过滤注释和空行
with open("requirements-build.txt") as f:
    build_requires = [
        line.strip() for line in f
        if line.strip() and not line.startswith("#")
    ]

# 更新build-system.requires
config["build-system"]["requires"] = build_requires

# 写回pyproject.toml
with open("pyproject.toml", "wb") as f:
    tomli_w.dump(config, f)

构建前先运行该脚本,再执行pip install .或python -m build。

方案2:利用Setuptools的构建钩子动态读取依赖

通过实现PEP 517的构建钩子函数,在构建时动态加载外部文件中的依赖:

  1. 在项目根目录创建setup.py:
from setuptools import setup

def get_requires_for_build_wheel(config_settings=None):
    # 读取构建依赖文件
    with open("requirements-build.txt") as f:
        return [
            line.strip() for line in f
            if line.strip() and not line.startswith("#")
        ]

setup(
    # 按需添加项目基本配置,或配合pyproject.toml的dynamic字段使用
    name="your-project-name",
    dynamic=["version", "description"]
)
  1. 配置pyproject.toml的构建系统:
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"

[project]
dynamic = ["version", "description"]
# 其他项目配置...

构建时,Setuptools会自动调用get_requires_for_build_wheel获取额外的构建依赖。

内容的提问来源于stack exchange,提问作者Anaphory

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:30:50