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

如何修改Python脚本获取指定Git分支的最新提交消息?

解决方法

原代码中branch.commit返回的是PyGithub的Commit对象,直接打印只会输出提交SHA标识。要获取提交消息,需要访问该对象的commit.message属性(commit是Commit对象内部存储提交元数据的子属性)。

修改后的完整代码

from github import Github
import sys
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

# GitHub连接配置
gc = Github(login_or_token='3d09afd6df8d92bd', password=None, base_url="https://eos2git.com/api/v3", timeout=60, verify=False, retry=5)
# 获取目标仓库
repo_gh = gc.get_repo('Devops/emporium')
# 遍历仓库分支
branches = repo_gh.get_branches()

for branch in branches:
    if branch.name == "dev/anjali-raghu/DSE-401":
        # 获取并打印最新提交消息
        print(branch.commit.commit.message)

关键修改说明

  • branch.commit拿到的是Commit对象,提交消息存储在该对象的commit.message字段中
  • 如果需要同时输出提交SHA和消息,可以调整打印逻辑:
    commit_obj = branch.commit
    print(f"提交SHA: {commit_obj.sha}")
    print(f"提交消息: {commit_obj.commit.message}")
    

优化方案(无需遍历所有分支)

直接通过分支名获取目标分支,避免遍历所有分支,效率更高且能处理分支不存在的异常:

from github import Github
import sys
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

gc = Github(login_or_token='3d09afd6df8d92bd', password=None, base_url="https://eos2git.com/api/v3", timeout=60, verify=False, retry=5)
repo_gh = gc.get_repo('Devops/emporium')

try:
    target_branch = repo_gh.get_branch("dev/anjali-raghu/DSE-401")
    print(target_branch.commit.commit.message)
except Exception as e:
    print(f"获取分支失败: {str(e)}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:26:26