4

I am trying to run git clone command using subprocess.check_output() so that I can verify if it clones successfully or not, but its throwing error.

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

I am doing:

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

How can I get the output of git clone so that I can verify it worked fine or not and can catch any errors if any.

Thanks

3
  • How are you running the git clone command? Like proc = subprocess.Popen(['git', 'clone', url], stdout=subprocess.PIPE)? Then you can use proc.stdout.read(). Commented Aug 22, 2018 at 8:29
  • @FHTMitchell I am using subprocess.check_output not with Popen, but I'll try it and will update. Commented Aug 22, 2018 at 8:30
  • @FHTMitchell Can you answer the question by giving an example Commented Aug 22, 2018 at 8:55

1 Answer 1

5

So the best method to read a subprocess' output is to use subprocess.PIPE. For example

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)

outputs:

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

Hence you can test success by changing the function to be

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
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. But I got output b"Cloning into 'Project'...\nfatal: I don't handle protocol 'git clone https'\n"
That's a git problem, not a python problem. What url did you pass?
But that same url is working fine on terminal without python :)
stackoverflow.com/questions/30474447/… sounds like you have a non-ascii character in there
Hi, it is so strange that when the clone succeed, it only prints the first line but in err: out = b'' err = b"Cloning into 'sshuttle'...\n", any suggestions?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.