问题
I am trying to get a list of all the branches available on my repository using Python with this code :
import subprocess
branches = ["All"]
command = "git branch -r"
branch_list = subprocess.check_output(command)
for branch in branch_list:
print branch
branches.append[branch]
What I want is to have something like :
print branches[0] # is "All"
print branches[1] # is "branch1"
print branches[2] # is "branch2"
etc etc
but instead of that I have
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
Thank you for your time and your help
回答1:
Taking a peek at the check_output documentation, it looks like we're getting a blob of bytes back. To make it easier to work with, we can decode it. Then, since git branch -r outputs one branch per line, split the string on newlines:
branches = subprocess.check_output(command).decode().split('\n')
BUT I think there's an even easier way to do it. Every single object in git corresponds to some file under the .git directory. In this case, you can find your list of branches in .git/refs/heads:
import os
branches = os.listdir('.git/refs/heads')
EDIT (2020/10/13): I've spent some more time with subprocess since writing this response and wanted to point out the text option (via subprocess.run):
If
encodingorerrorsare specified, ortextis true, file objects for stdin, stdout and stderr are opened in text mode using the specified encoding and errors or theio.TextIOWrapperdefault.
This means you could write the check_output expression as:
branches = subprocess.check_output(command, text=True).split('\n')
leaving encoding and decoding to the system. Whichever you prefer!
回答2:
Try decodeing it:
stdout = subprocess.check_output('git branch -a'.split())
out = stdout.decode()
branches = [b.strip('* ') for b in out.splitlines()]
print(branches)
output:
['master', 'second', 'test']
回答3:
For 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)
For python2, replace subprocess with commands.
来源:https://stackoverflow.com/questions/56905963/how-to-get-a-list-of-a-repository-branches-using-python