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

如何在Setuptools配置中复用Poetry的[tool.poetry.dependencies]

复用Poetry依赖到Setuptools的[project]区块

方法1:用Poetry导出命令快速转换依赖格式

Poetry自带的poetry export命令可以把依赖转换成标准的requirements格式,你可以把输出调整成PEP 621要求的数组格式:

  1. 运行以下命令生成符合格式的依赖列表:
poetry export --format=requirements.txt --without-hashes | sed -e 's/^/"/' -e 's/$/",/'
  1. 把输出的内容复制粘贴到pyproject.toml的[project].dependencies数组中。
  2. 手动处理Python版本限制:将[tool.poetry.dependencies]里的python = "^3.12"转换成[project]里的requires-python = ">=3.12"。

方法2:写Python脚本自动同步依赖

如果需要频繁更新依赖,手动复制太麻烦,可以写个简单的Python脚本自动读取Poetry的依赖区块,转换格式后写入Setuptools的[project]区块:

import tomli
import tomli_w

def sync_poetry_to_setuptools():
    # 读取pyproject.toml
    with open("pyproject.toml", "rb") as f:
        config = tomli.load(f)
    
    poetry_deps = config["tool"]["poetry"]["dependencies"]
    project_deps = []
    
    for dep_name, dep_spec in poetry_deps.items():
        if dep_name == "python":
            # 处理Python版本要求
            config["project"]["requires-python"] = dep_spec.replace("^", ">=")
            continue
        
        # 处理普通依赖
        if isinstance(dep_spec, str):
            project_deps.append(f"{dep_name}{dep_spec}")
        # 处理带环境标记的复杂依赖(比如Poetry的字典格式)
        elif isinstance(dep_spec, dict):
            dep_str = f"{dep_name}{dep_spec['version']}"
            if "python" in dep_spec:
                # 转换Poetry的Python版本约束到PEP 508格式
                py_constraint = dep_spec["python"].replace("^", ">=")
                dep_str += f"; python_version {py_constraint}"
            project_deps.append(dep_str)
    
    # 更新[project]的dependencies字段
    config["project"]["dependencies"] = project_deps
    
    # 写回pyproject.toml
    with open("pyproject.toml", "wb") as f:
        tomli_w.dump(config, f)

if __name__ == "__main__":
    sync_poetry_to_setuptools()

使用前确保安装依赖:

pip install tomli tomli-w

每次更新Poetry依赖后,运行这个脚本就能自动同步到Setuptools的配置区块。

方法3:直接用Poetry打包(无需额外配置Setuptools)

其实Poetry本身支持生成符合PyPI标准的wheel和sdist包,直接运行poetry build就能生成可通过pip install安装的包,不需要单独配置Setuptools的[project]区块。如果你的需求只是让包能被pip安装,这可能是最省心的方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 16:13:11