我正在尝试使用 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
感谢您的时间和帮助
浏览一下check_output
文档 https://docs.python.org/3/library/subprocess.html#subprocess.check_output,看起来我们正在返回一团字节。为了更容易使用,我们可以对其进行解码。然后,自从git branch -r
每行输出一个分支,在换行符上分割字符串:
branches = subprocess.check_output(command).decode().split('\n')
但我认为有一种更简单的方法可以做到这一点。 git 中的每个对象都对应于.git
目录。在这种情况下,您可以在以下位置找到您的分支机构列表:.git/refs/heads
:
import os
branches = os.listdir('.git/refs/heads')
编辑(2020/10/13):我花了更多时间subprocess
自从写这篇回复以来,我想指出text
选项(通过subprocess.run
):
If encoding
or errors
已指定,或text
为 true 时,将使用指定的编码和错误或在文本模式下打开 stdin、stdout 和 stderr 的文件对象io.TextIOWrapper
默认。
这意味着你可以写check_output
表达式为:
branches = subprocess.check_output(command, text=True).split('\n')
将编码和解码留给系统。无论你喜欢哪个!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)