【问题标题】:How to capture the output of git clone command running from python subprocess如何捕获从 python 子进程运行的 git clone 命令的输出
【发布时间】:2019-01-28 11:14:00
【问题描述】:

我正在尝试使用subprocess.check_output() 运行git clone 命令,以便我可以验证它是否成功克隆,但它的抛出错误。

Command 'git clone <url>' returned non-zero exit status 128

我在做:

resp = subprocess.check_output('git clone <url>', shell=True)

如何获取 git clone 的输出,以便验证它是否正常工作,并且可以捕获任何错误(如果有)。

谢谢

【问题讨论】:

  • 你是如何运行 git clone 命令的?喜欢proc = subprocess.Popen(['git', 'clone', url], stdout=subprocess.PIPE)?然后你可以使用proc.stdout.read()
  • @FHTMitchell 我正在使用 subprocess.check_output 而不是 Popen,但我会尝试并更新。
  • @FHTMitchell 你能举个例子回答一下吗

标签: python git subprocess


【解决方案1】:

所以读取子进程输出的最佳方法是使用subprocess.PIPE。例如

import subprocess
from collections import namedtuple

def git_clone(url):
    process = subprocess.Popen(['git', 'clone', url], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return namedtuple('Std', 'out, err')(process.stdout.read(), process.stderr.read())

# test on fake url
out, err = git_clone('http://fake.url')
print('out = {}\nerr = {}'.format(out, err)

输出:

out = b''
err = b"Cloning into 'fake.url'...\nfatal: unable to access 'http://fake.url/': Couldn't resolve host 'fake.url'\n"

因此您可以通过将函数更改为来测试成功

from warnings import warn

def git_clone(url):

    process = subprocess.Popen(['git', 'clone', url], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    if not process.stdout.read():
        warn(process.stderr.read())
        return False

    return True

【讨论】:

  • 谢谢。但我得到了输出b"Cloning into 'Project'...\nfatal: I don't handle protocol 'git clone https'\n"
  • 这是 git 问题,不是 python 问题。你传的是什么网址?
  • 但是同样的 url 在没有 python 的终端上可以正常工作:)
  • stackoverflow.com/questions/30474447/… 听起来你里面有一个非 ascii 字符
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
  • 1970-01-01
  • 2016-10-06
  • 2015-08-20
  • 2018-01-28
  • 1970-01-01
  • 2018-05-20
相关资源
最近更新 更多