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

Windows-latest环境GitHub Actions中Python脚本输出为空的解决方法

解决Windows环境GitHub Actions中Python脚本输出为空的问题

问题场景

在windows-latest环境的GitHub Actions工作流中,执行Python脚本后需要获取其输出的0-4整数,若输出不为0则终止工作流。但当前传递到后续步骤的输出值为空字符串,导致判断逻辑出错。

原工作流代码

name: Workflow
on: [push]

permissions:
  id-token: write
  contents: read

jobs:
  workflow:
    runs-on: windows-latest
    steps:
      - name: Check out repository
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          ...

      - name: Run code
        id: exit_code
        run: |
          $result = python test/test_1.py
          echo "my_output=$result" >> "$GITHUB_OUTPUT"

      - name: Check Output and Fail if Not Equal to 0
        shell: bash
        run: |
          output_value="${{ steps.exit_code.outputs.my_output }}"
          if [[ "$output_value" != "0" ]]; then
            echo "Output value is not 0. Failing the action."
            exit 1
          else
            echo "Output value is 0. Continuing with the action."
          fi

错误信息

Run if [[ "" -ne "0" ]]; then
  if [[ "" -ne "0" ]]; then
    echo "Output value is not 0. Failing the action."
    exit 1
  else
    echo "Output value is 0. Continuing with the action."
  fi
  shell: C:\Program Files\Git\bin\bash.EXE --noprofile --norc -e -o pipefail {0}

原Python脚本写法

写法1

...

def test():
    ...

    return exit_code


if __name__ == "__main__":
    exit_code_final = test()
    print(exit_code_final)

写法2

...

def test():
    ...

    return exit_code


if __name__ == "__main__":
    print(test())

解决方案

1. 修正PowerShell输出捕获逻辑

Windows环境下PowerShell执行Python脚本时,捕获的输出可能包含多余的换行、空格或空白字符,导致写入GITHUB_OUTPUT的内容无效。修改Run code步骤的脚本,对捕获的输出进行修剪:

- name: Run code
  id: exit_code
  run: |
    # 捕获Python输出并去除前后空白字符
    $result = (python test/test_1.py).Trim()
    # 确保输出不为空时写入GITHUB_OUTPUT,为空则强制写入非0值触发失败
    if (-not [string]::IsNullOrEmpty($result)) {
      echo "my_output=$result" >> "$GITHUB_OUTPUT"
    } else {
      echo "my_output=1" >> "$GITHUB_OUTPUT"
    }

2. 确保Python脚本仅输出目标整数

检查Python脚本是否存在额外的print语句(如调试日志、警告信息),这些内容会混入输出导致捕获的值不符合预期。确保脚本仅打印最终的0-4整数,无其他输出。

3. 可选:统一使用Bash执行脚本

如果PowerShell的输出捕获问题难以排查,可以将Run code步骤切换为Bash shell,避免跨shell的输出处理差异:

- name: Run code
  id: exit_code
  shell: bash
  run: |
    # 去除输出中的换行符,确保只保留整数
    result=$(python test/test_1.py | tr -d '\r\n')
    echo "my_output=$result" >> "$GITHUB_OUTPUT"

验证修改

修改后重新触发工作流,后续步骤的output_value将正确获取Python脚本输出的整数,判断逻辑会正常执行:

  • 若输出为0,工作流继续;
  • 若输出为1-4或为空,工作流终止并提示错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 13:07:33