如何使用Python获取存储库分支的列表

时间:2019-07-05 15:39:55

标签: python git subprocess

我正在尝试使用Python通过以下代码获取存储库中所有可用分支的列表:

import subprocess

branches = ["All"]
command = "git branch -r"
branch_list = subprocess.check_output(command)

for branch in branch_list:
   print branch
   branches.append[branch]

我想要的是类似的东西:

print branches[0] # is "All"
print branches[1] # is "branch1"
print branches[2] # is "branch2"
etc etc

但我有

print branches[0] # is "All"
print branches[1] # is "b"
print branches[2] # is "r"
print branches[3] # is "a"
print branches[4] # is "n"
print branches[5] # is "c"
print branches[6] # is "h"
etc etc

感谢您的时间和帮助

3 个答案:

答案 0 :(得分:3)

窥视check_output documentation,看来我们又收到了一堆字节。为了使其更易于使用,我们可以对其进行解码。然后,由于git branch -r每行输出一个分支,因此请在换行符上分割字符串:

branches = subprocess.check_output(command).decode().split('\n')

但是我认为有一种更简单的方法可以做到。 git中的每个对象都对应于.git目录下的某个文件。在这种情况下,您可以在.git/refs/heads中找到分支机构列表:

import os
branches = os.listdir('.git/refs/heads')

答案 1 :(得分:2)

尝试decode添加它:

stdout = subprocess.check_output('git branch -a'.split())
out = stdout.decode()
branches = [b.strip('* ') for b in out.splitlines()]
print(branches)

输出:

['master', 'second', 'test']

答案 2 :(得分:0)

对于python3,

import subprocess

# refs/remotes for remote tracking branches.
# refs/heads for local branches if necessary, and
# refs/tags for tags
cmd = 'git for-each-ref refs/remotes --format="%(refname)"'
status, output = subprocess.getstatusoutput(cmd)
branches = ["All"]
if status == 0:
    branches += output.split('\n')
print(branches)

对于python2,将subprocess替换为commands