如何使用Python克隆git仓库,并获取克隆进度?

12

我希望可以使用Python通过某个库来git clone一个大型代码库,但是我需要能够在clone的过程中实时查看进度。我尝试了pygit2和GitPython,但它们似乎没有显示进度的功能。是否有其他方法可用?


你想以什么方式显示进度?在GUI界面上还是在stdout输出中? - Robᵩ
http://stackoverflow.com/questions/23155452/read-git-clones-output-in-real-time - David Neiss
@Robᵩ,我想的是CLI git命令通常显示进度的方式,例如抓取对象11/27... - Jonathan
2个回答

13
您可以使用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

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。此标志即使标准错误流未连接到终端也会强制显示进度状态。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接