我在这个模块中没有看到检出或列出远程/本地分支的选项:https://gitpython.readthedocs.io/en/stable/
对于那些只想打印远程分支的人:
# Execute from the repository root directory
repo = git.Repo('.')
remote_refs = repo.remote().refs
for refs in remote_refs:
print(refs.name)
要列出分支,您可以使用以下命令:
from git import Repo
r = Repo(your_repo_path)
repo_heads = r.heads # or it's alias: r.branches
r.heads
返回 git.util.IterableList
(继承自 list
)的 git.Head
对象,因此您可以:
repo_heads_names = [h.name for h in repo_heads]
并且要检出例如 master
:
repo_heads['master'].checkout()
# you can get elements of IterableList through it_list['branch_name']
# or it_list.branch_name
完成以下步骤后
from git import Git
g = Git()
(并可能使用其他命令来将g
初始化到您关心的存储库)对g
的所有属性请求都或多或少地转换为调用git attr *args
。
因此:
g.checkout("mybranch")
应该做你想要的事情。
g.branch()
repo.py
中有一个特殊的active_branch
命令。您需要查看源代码并自己找到它。我也遇到了类似的问题。在我的情况下,我只想列出本地跟踪的远程分支。这个方法对我有效:
import git
repo = git.Repo(repo_path)
branches = []
for r in repo.branches:
branches.append(r)
# check if a tracking branch exists
tb = t.tracking_branch()
if tb:
branches.append(tb)
def get_all_branches(path):
cmd = ['git', '-C', path, 'branch', '-a']
out = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
return out
repo.git.branch('-a')
。 - dusktreader为了让它更加明显 - 要从当前仓库目录获取远程分支列表:
import os, git
# Create repo for current directory
repo = git.Repo(os.getcwd())
# Run "git branch -r" and collect results into array
remote_branches = []
for ref in repo.git.branch('-r').split('\n'):
print(ref)
remote_branches.append(ref)
repo = git.Repo()
repo.git.checkout('-b', local_branch, remote_branch)
local_branch
(如果已经存在,则会引发错误),并设置为跟踪远程分支remote_branch
。我在这里采用了稍微不同的方法,基于获取一个可检出分支列表的愿望:
repo = git.Repo(YOUR_REPO_HERE)
branch_list = [r.remote_head for r in repo.remote().refs]
与使用refs.name
的答案不同,这个方法获取的名称不带远程前缀,以您想要用于检出存储库的形式呈现。