如何使用Python获取存储库分支的列表 [英] How to get a list of a repository branches using Python
问题描述
我正在尝试使用Python通过以下代码获取存储库中所有可用分支的列表:
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
但是我有
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
感谢您的时间和帮助
推荐答案
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')
但是我认为有一种更简单的方法可以做到这一点.git中的每个对象都对应于 .git
目录下的某个文件.在这种情况下,您可以在 .git/refs/heads
中找到分支列表:
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')
编辑(2020/10/13):自编写此响应以来,我在 subprocess
上花费了更多时间,并想指出 text
选项(通过 subprocess.run
):
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
):
如果指定了
encoding
或errors
,或者text
为true,则使用以下命令在文本模式下打开stdin,stdout和stderr的文件对象指定的编码和错误或io.TextIOWrapper
默认值.
If
encoding
orerrors
are specified, ortext
is true, file objects for stdin, stdout and stderr are opened in text mode using the specified encoding and errors or theio.TextIOWrapper
default.
这意味着您可以将 check_output
表达式编写为:
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!
这篇关于如何使用Python获取存储库分支的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!