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

如何用Python查询GitHub CI结果,仅对通过CI的PR执行测试?

使用PyGithub查询Pull Request的CI结果

完全可以通过PyGithub实现查询PR的CI结果,下面给你两种实用的实现方式:

方式一:检查PR头部提交的合并状态

这种方式会汇总该PR头部提交的所有CI检查结果,返回整体状态:

from github import Github

# 初始化客户端,替换为你的GitHub访问令牌
g = Github("your_github_access_token")
repo = g.get_repo("你的仓库所有者/仓库名称")

# 遍历目标PR(这里以开放状态的PR为例,可按需调整state参数)
for pull in repo.get_pulls(state="open"):
    # 获取PR头部提交的合并状态
    combined_status = repo.get_combined_status(pull.head.sha)
    # 判断整体CI是否全部通过
    if combined_status.state == "success":
        # 在这里执行你的测试逻辑
        print(f"PR #{pull.number} 已通过所有CI检查,开始执行测试")

方式二:检查特定CI任务的结果

如果只需要验证某个特定的CI任务(比如名为"Unit Tests"的检查)是否通过,可以用get_check_runs()方法:

from github import Github

g = Github("your_github_access_token")
repo = g.get_repo("你的仓库所有者/仓库名称")

target_ci_name = "Unit Tests"  # 替换为你要检查的CI任务名称

for pull in repo.get_pulls(state="open"):
    check_runs = pull.get_check_runs()
    # 检查目标CI任务是否已完成且成功
    ci_task_passed = any(
        run.name == target_ci_name 
        and run.status == "completed" 
        and run.conclusion == "success"
        for run in check_runs
    )
    if ci_task_passed:
        print(f"PR #{pull.number} 的{target_ci_name}已通过,执行测试")

注意事项

  • 确保你的GitHub访问令牌拥有repo权限,否则无法查询CI状态
  • get_combined_status()返回的state值包括success(全部通过)、failure(至少一项失败)、pending(有检查在运行)等
  • 若要筛选特定状态的PR,可调整get_pulls()的state参数,可选值为open、closed、all

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:57:14