Как получить список веток хранилища с использованием Python - PullRequest
1 голос
/ 05 июля 2019

Я пытаюсь получить список всех веток, доступных в моем репозитории, используя 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 ]

3 голосов
/ 05 июля 2019

Взглянув на документацию 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')
2 голосов
/ 05 июля 2019

Попробуйте decode ing it:

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

Вывод:

['master', 'second', 'test']
0 голосов
/ 06 июля 2019

Для 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.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...