如何从GitHub仓库获取所有分支的完整列表?
实现方案
你可以通过以下两种方式实现需求,最终生成的branches变量为分支名称组成的列表,直接通过索引取值即可调用:
方案1:使用PyGitHub SDK(推荐)
- 安装依赖
执行命令:pip install PyGitHub - 代码示例
from github import Github # 访问私有仓库需传入个人访问令牌,访问公开仓库可留空写为 g = Github() g = Github("你的GitHub个人访问令牌(可选)") # 替换为目标仓库的所有者和仓库名,例:octocat/Hello-World repo = g.get_repo("所有者用户名/仓库名") # 生成分支名称列表 branches = [branch.name for branch in repo.get_branches()] # 测试调用 print(branches[1])
方案2:直接调用GitHub REST API(无需GitHub专属SDK)
- 安装依赖
执行命令:pip install requests - 代码示例
import requests owner = "所有者用户名" repo = "仓库名" # 访问私有仓库需在headers新增Authorization参数:{"Authorization": "token 你的个人访问令牌"} resp = requests.get(f"https://api.github.com/repos/{owner}/{repo}/branches") resp.raise_for_status() branches = [item["name"] for item in resp.json()] # 测试调用 print(branches[1])
注意事项
- 未认证状态下GitHub API每小时请求上限为60次,有高频请求需求建议传入个人访问令牌,上限可提升至每小时5000次
- 分支列表默认按字母顺序排序,和GitHub仓库页面展示的分支顺序一致
内容的提问来源于stack exchange,提问作者william
相关产品推荐
相关产品推荐

