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

PyGithub操作:如何切换分支并查看子文件夹内容

解决PyGithub切换分支及目录内容查看问题

你当前的代码已经能获取仓库和分支列表,要实现切换分支、查看分支内容等操作,核心是在调用get_contents()时指定ref参数(分支名),同时处理目录的递归遍历。以下是完整实现代码:

from github import Github

access_token = "MYACCESS_TOKEN"
g = Github(access_token, retry=20)

# 获取仓库对象
repo = g.get_repo("pygit/git")
print(f"仓库名称: {repo.name}")

# 1. 列出所有分支【已完成】
print("\n所有分支:")
branches = repo.get_branches()
branch_names = [branch.name for branch in branches]
for branch in branches:
    print(branch.name)

# 2. 切换到指定分支(这里以"main"为例,可替换为目标分支名)
target_branch = "main"
if target_branch not in branch_names:
    print(f"\n错误:分支 {target_branch} 不存在")
else:
    # 3. 查看该分支下包含目录在内的所有内容(递归遍历)
    def get_all_contents(path, branch):
        contents = repo.get_contents(path, ref=branch)
        for item in contents:
            print(f"[{item.type}] {item.path}")
            if item.type == "dir":
                get_all_contents(item.path, branch)

    print(f"\n分支 {target_branch} 下的所有内容:")
    get_all_contents("", target_branch)

    # 4. 进入指定目录(这里以"docs"为例,可替换为目标目录)
    target_dir = "docs"
    # 5. 查看该目录下的所有内容
    print(f"\n分支 {target_branch} 中 {target_dir} 目录下的内容:")
    try:
        dir_contents = repo.get_contents(target_dir, ref=target_branch)
        for item in dir_contents:
            print(f"[{item.type}] {item.name}")
    except Exception as e:
        print(f"错误:目录 {target_dir} 不存在或无法访问 - {str(e)}")

关键说明:

  • 切换分支:PyGithub没有单独的"切换分支"操作,只需在get_contents()中通过ref参数指定目标分支名,就能获取对应分支的内容。
  • 递归遍历全部分支内容:通过自定义递归函数get_all_contents(),遇到目录类型的条目就继续深入遍历,实现完整的内容列表输出。
  • 查看指定目录:直接给get_contents()传入目标目录路径和分支名,即可获取该目录下的所有文件与子目录。

内容的提问来源于stack exchange,提问作者MLS Mahesh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:40:25