如何在GitHub Actions中传递Python多行错误信息至PR评论?
解决GitHub Actions中多行环境变量传递及PR多行评论问题
问题背景
在GitHub Actions工作流中,通过Invoke命令调用Python脚本生成错误列表,尝试将带换行的错误字符串写入GITHUB_ENV环境变量文件,传递给后续步骤使用actions/github-script在PR中添加多行评论。但执行Python脚本时触发报错:
Error: Unable to process file command 'env' successfully. Error: Invalid format 'You are too young'
去掉换行后流程正常,但无法实现多行评论效果。
错误原因
GitHub Actions的GITHUB_ENV文件要求每行必须是KEY=VALUE的格式,若VALUE包含换行,直接写入会导致换行后的内容被识别为新的环境变量定义行,从而触发格式错误。原脚本中直接用换行拼接错误字符串写入,第二行错误信息被当作新的环境变量,因此报错。
修正方案
1. 调整Python脚本的环境变量写入格式
使用GitHub支持的多行环境变量语法,用分界符(如EOF)包裹带换行的内容,确保换行被正确识别为VALUE的一部分。修改后的Python脚本:
import os from invoke import task, Context @task def set_errors(ctx: Context): # 示例错误列表 my_errors_list = [ "You have invalid email", "You are too young", "You are using the wrong provider for your rides" ] my_errors_string = '\n'.join(my_errors_list) file_path: str = os.environ.get('GITHUB_ENV', None) if file_path is None: raise OSError('Environment file not found') # 采用多行环境变量格式写入 with open(file_path, 'a') as gh_envs: gh_envs.write('ERROR_LIST<<EOF\n') gh_envs.write(my_errors_string + '\n') gh_envs.write('EOF\n')
2. 修正github-script的变量引用方式
在github-script中,需将环境变量内容用模板字符串包裹,避免换行导致的JavaScript语法错误。修改后的工作流步骤:
- name: Add comment uses: actions/github-script@v6 with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | github.rest.issues.createComment({ issue_number: ${{ github.event.issue.number || github.event.number }}, owner: context.repo.owner, repo: context.repo.repo, body: `${{ env.ERROR_LIST }}` })
替代方案(直接在Python脚本中添加PR评论)
若不想通过环境变量传递内容,可直接在Python脚本中调用GitHub API完成PR评论,减少中间环节:
- 工作流中添加依赖安装步骤:
- name: Install required packages run: pip install invoke pygithub
- 修改Python脚本,直接调用GitHub API:
import os from invoke import task, Context from github import Github @task def set_errors(ctx: Context): my_errors_list = [ "You have invalid email", "You are too young", "You are using the wrong provider for your rides" ] my_errors_string = '\n'.join(my_errors_list) # 初始化GitHub客户端 g = Github(os.environ.get('GITHUB_TOKEN')) repo = g.get_repo(os.environ.get('GITHUB_REPOSITORY')) pr_number = int(os.environ.get('PR_NUMBER')) # 给PR添加评论 pr = repo.get_pull(pr_number) pr.create_issue_comment(my_errors_string)
- 工作流中调用脚本时传递必要环境变量:
- name: Run python script run: inv return-errors.set-errors env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_REPOSITORY: ${{ github.repository }} PR_NUMBER: ${{ github.event.issue.number || github.event.number }}
内容的提问来源于stack exchange,提问作者Phoen
相关产品推荐
相关产品推荐

