如何使用python git克隆存储库,并获取克隆过程的进度?

时间:2016-08-05 03:37:54

标签: python git

我希望能够使用python克隆一个大型存储库,使用一些库,但重要的是我希望能够看到克隆的进展,因为它正在发生。我试过pygit2和GitPython,但他们似乎没有表现出他们的进步。还有另外一种方法吗?

2 个答案:

答案 0 :(得分:3)

您可以使用RemoteProgress中的GitPython。这是一个粗略的例子:

import git

class Progress(git.remote.RemoteProgress):
    def update(self, op_code, cur_count, max_count=None, message=''):
        print 'update(%s, %s, %s, %s)'%(op_code, cur_count, max_count, message)

repo = git.Repo.clone_from(
    'https://github.com/gitpython-developers/GitPython',
    './git-python',
    progress=Progress())

或者使用此update()函数获得更精确的消息格式:

    def update(self, op_code, cur_count, max_count=None, message=''):
        print self._cur_line

答案 1 :(得分:2)

如果您只想获取克隆信息,而无需安装gitpython,则可以通过内置的subprocess模块直接从标准错误流中获取它。

import os
from subprocess import Popen, PIPE, STDOUT

os.chdir(r"C:\Users")  # The repo storage directory you want

url = "https://github.com/USER/REPO.git"  # Target clone repo address

proc = Popen(
    ["git", "clone", "--progress", url],
    stdout=PIPE, stderr=STDOUT, shell=True, text=True
)

for line in proc.stdout:
    if line:
        print(line.strip())  # Now you get all terminal clone output text

执行命令git help clone后,您可以看到一些克隆命令的相关信息。

--progress

默认情况下在标准错误流上报告进度状态 当它连接到终端时,除非指定了--quiet。这个 该标志强制进度状态,即使标准错误流不是 定向到终端。