如何使用PyGithub基于master分支创建新分支并检出?
使用PyGithub基于master分支创建并检出新分支
操作步骤与代码示例
认证并连接仓库
通过个人访问令牌完成GitHub认证,获取目标仓库对象:from github import Github # 替换为你的个人访问令牌 g = Github("your-personal-access-token") # 替换为你的用户名和仓库名称 repo = g.get_repo("your-username/your-repository")获取master分支的最新提交
拿到master分支的最新提交SHA,作为新分支的创建起点:master_branch = repo.get_branch("master") master_latest_sha = master_branch.commit.sha创建远程新分支
调用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)本地检出分支
PyGithub仅负责远程仓库操作,本地分支检出需要用原生Git命令:git fetch origin git checkout feature/your-new-branch
注意事项
- 确保个人访问令牌拥有仓库的写入权限,否则无法创建分支
- 若仓库默认分支不是
master(比如main),替换成对应的分支名即可
内容的提问来源于stack exchange,提问作者Kay
相关产品推荐
相关产品推荐

