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

如何基于Python脚本输出终止windows-latest上的GitHub Actions工作流

GitHub Actions工作流修复方案

问题根源

  1. Shell语法不兼容:工作流运行在windows-latest环境,默认使用PowerShell执行run步骤,但校验步骤写的是Bash语法,导致PowerShell解析报错。
  2. 输出捕获不完整:Python脚本的输出可能包含换行或空白字符,直接赋值会导致写入GITHUB_OUTPUT的内容带空白,甚至为空。

修复步骤

1. 修正Python输出捕获逻辑

在「Run code」步骤中,对Python输出做去空白处理,确保捕获到纯净的整数:

- name: Run code
  id: exit_code
  run: |
    # Trim()移除输出中的换行、空格等空白字符
    $result = (python test/test_1.py).Trim()
    echo "my_output=$result" >> "$env:GITHUB_OUTPUT"

2. 替换校验步骤为PowerShell语法

把原Bash风格的校验逻辑改成PowerShell兼容的写法:

- name: Check Output and Fail if Not Equal to 0
  run: |
    $output_value = "${{ steps.exit_code.outputs.my_output }}"
    if ($output_value -ne 0) {
        Write-Host "Output value is not 0. Failing the action."
        exit 1
    } else {
        Write-Host "Output value is 0. Continuing with the action."
    }

替代方案:直接使用Python进程退出码

如果Python脚本的输出值和进程退出码一致,可以简化流程,无需捕获输出,直接利用GitHub Actions对进程退出码的判断:
修改Python脚本,用sys.exit()返回退出码:

import sys

def test():
    ...
    return exit_code

if __name__ == "__main__":
    exit_code_final = test()
    print(exit_code_final)
    sys.exit(exit_code_final)

然后移除「Check Output」步骤,GitHub Actions会自动在Python脚本返回非0退出码时终止工作流:

- name: Run code
  run: python test/test_1.py

内容的提问来源于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 20:03:18