S A*_*rew 4 python git subprocess
我正在尝试git clone使用运行命令subprocess.check_output(),以便我可以验证它是否克隆成功,但它抛出错误。
Command 'git clone <url>' returned non-zero exit status 128
Run Code Online (Sandbox Code Playgroud)
我在做:
resp = subprocess.check_output('git clone <url>', shell=True)
Run Code Online (Sandbox Code Playgroud)
我怎样才能获得 git clone 的输出,以便我可以验证它是否正常工作,并可以捕获任何错误(如果有)。
谢谢
因此,读取子进程输出的最佳方法是使用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)
Run Code Online (Sandbox Code Playgroud)
输出:
out = b''
err = b"Cloning into 'fake.url'...\nfatal: unable to access 'http://fake.url/': Couldn't resolve host 'fake.url'\n"
Run Code Online (Sandbox Code Playgroud)
因此,您可以通过将函数更改为来测试成功
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
Run Code Online (Sandbox Code Playgroud)