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

GitHub Actions问题:Poetry已装Black但CI工作流无法找到

GitHub Actions中Poetry环境下找不到Black工具的解决办法

问题背景

使用Poetry管理Python项目环境,本地pre-commit代码质量工作流运行正常,但在GitHub Actions(GHA)中,尽管日志明确显示Black已成功安装,执行black 'src'时却提示black: command not found。

相关配置文件(codequal.yml)

name: Python QA

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

permissions:
  contents: read

jobs:
  pylint:
    runs-on: ubuntu-latest
    name: Python QA

    steps:
    - name: Check out
      uses: actions/checkout@v3

    - name: Set up Python 3.10
      uses: actions/setup-python@v4
      with:
        python-version: "3.10"

    - name: cache poetry install
      uses: actions/cache@v3
      with:
        path: ~/.local
        key: poetry-1.3.2

    - uses: snok/install-poetry@v1.3.3
      with:
        version: 1.3.2
        virtualenvs-create: true
        virtualenvs-in-project: true
        installer-parallel: true

    - name: cache deps
      id: cache-deps
      uses: actions/cache@v3
      with:
        path: .venv
        key: pydeps-${{ hashFiles('**/poetry.lock') }}

    - run: poetry install --no-interaction --no-root
      if: steps.cache-deps.outputs.cache-hit != 'true'

    - run: poetry install --no-interaction

    - name: Format with black
      run: |
        black 'src'

    - name: Lint with pylint
      run: |
        pylint --fail-under=7.0 --recursive=y --enable=W 'src'

GHA日志关键片段

Run poetry install --no-interaction --no-root
Creating virtualenv rssita in /home/runner/work/rssita/rssita/.venv
Installing dependencies from lock file

Package operations: 49 installs, 1 update, 0 removals
...
  • Installing black (22.12.0)
...
Run black 'src'
/home/runner/work/_temp/0fc25aa8-4903-45ae-9d8e-9c11f60dca11.sh: line 1: black: command not found
Error: Process completed with exit code 127.

原因

GitHub Actions的默认Shell未激活Poetry创建的本地虚拟环境(.venv目录),直接执行black命令时,系统会在全局环境中查找,而工具实际安装在项目的虚拟环境内,因此找不到命令。

解决方法

方法1:用poetry run前缀执行工具(推荐)

通过poetry run让Poetry自动在虚拟环境中运行指定工具,无需手动激活环境。修改工作流中执行代码质量工具的步骤:

- name: Format with black
  run: |
    poetry run black 'src'

- name: Lint with pylint
  run: |
    poetry run pylint --fail-under=7.0 --recursive=y --enable=W 'src'

方法2:手动激活虚拟环境

在执行命令前先激活项目内的虚拟环境,适用于需要连续执行多个工具的场景:

- name: Format with black
  run: |
    source .venv/bin/activate
    black 'src'

- name: Lint with pylint
  run: |
    source .venv/bin/activate
    pylint --fail-under=7.0 --recursive=y --enable=W 'src'

验证

修改后的工作流会正确找到虚拟环境中的Black和pylint工具,完成代码质量检查任务。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 05:50:27