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

能否使用pip安装Poetry的特定分组依赖?

如何用pip安装Poetry分组的依赖?

我按照Poetry的建议,用分组管理开发专属依赖(“test”“docs”“dev”),希望在GitHub Actions、Read the Docs和Nox这类依赖pip安装的自动化工具中使用这些分组,请问能不能像基于setuptools的包那样,用pip install my_lib[dev]这种方式安装特定分组?


可以实现,但需要先让Poetry的分组兼容pip的extras机制,具体操作如下:

核心原理

Poetry的依赖分组会在构建标准Python包(wheel/sdist)时,自动映射为pip支持的extras。所以只要把Poetry项目转换成pip可识别的包格式,就能用类似pip install my_lib[dev]的命令安装指定分组。

具体操作方法

1. 构建标准包后安装

先通过Poetry构建wheel或sdist包:

poetry build

构建完成后,dist/目录下会生成对应的包文件,此时就可以用pip安装指定分组:

# 安装dev分组依赖
pip install dist/my_lib-*.whl[dev]
# 或者安装test分组
pip install dist/my_lib-*.tar.gz[test]

2. 导出分组依赖到requirements文件

如果不想构建包,也可以直接导出指定分组的依赖到requirements文件,再用pip安装:

# 导出dev分组的依赖到requirements-dev.txt
poetry export --with dev --format requirements.txt --output requirements-dev.txt
# 用pip安装
pip install -r requirements-dev.txt

同样可以替换--with dev为--with test或--with docs来导出对应分组的依赖。

3. 自动化场景中的使用示例

  • GitHub Actions:在工作流中先构建包,再安装指定分组
    - name: Build package
      run: poetry build
    - name: Install with dev dependencies
      run: pip install dist/my_lib-*.whl[dev]
    
  • Read the Docs:在项目的.readthedocs.yaml中配置安装命令
    python:
      install:
        - method: pip
          path: .
          extra_requirements:
            - docs
    
  • Nox:在会话中直接安装带分组的项目
    def test(session):
        session.install(".[test]")
        # 后续测试命令
    

注意事项

  • 确保使用较新版本的pip(≥21.0),旧版本对pyproject.toml的extras支持可能存在问题。
  • 确认pyproject.toml中的分组配置正确,比如[tool.poetry.group.dev.dependencies]这种格式,才能被正确映射为pip的extras。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 14:45:10