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

如何使用PyGithub基于master分支创建新分支并检出?

使用PyGithub基于master分支创建并检出新分支

操作步骤与代码示例

  1. 认证并连接仓库
    通过个人访问令牌完成GitHub认证,获取目标仓库对象:

    from github import Github
    
    # 替换为你的个人访问令牌
    g = Github("your-personal-access-token")
    # 替换为你的用户名和仓库名称
    repo = g.get_repo("your-username/your-repository")
    
  2. 获取master分支的最新提交
    拿到master分支的最新提交SHA,作为新分支的创建起点:

    master_branch = repo.get_branch("master")
    master_latest_sha = master_branch.commit.sha
    
  3. 创建远程新分支
    调用create_git_ref方法创建分支,注意分支引用格式必须是refs/heads/分支名:

    new_branch_name = "feature/your-new-branch"
    repo.create_git_ref(ref=f"refs/heads/{new_branch_name}", sha=master_latest_sha)
    
  4. 本地检出分支
    PyGithub仅负责远程仓库操作,本地分支检出需要用原生Git命令:

    git fetch origin
    git checkout feature/your-new-branch
    

注意事项

  • 确保个人访问令牌拥有仓库的写入权限,否则无法创建分支
  • 若仓库默认分支不是master(比如main),替换成对应的分支名即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 12:59:15