简体   繁体   中英

Capturing git command output with subprocess

I'm trying to return all git commit hashes for commits that contain 'As delivered' in their commit message. Essentially, I want to capture the output of the below git command:

git log --all -i --grep 'As Delivered' --format='%H'

The above git command runs as I expect it to in the command line, returning one matched hash per output line. Here's the code I'm trying to use to accomplish my goal:

def getHashesMatchingGrep(grepStr="As Delivered"):
    grep_option = '--grep=\'' + grepStr + '\''
    format_option = '--format="' + '%H' + '"'
    cmd = ['git', 'log', '--all', '-i', grep_option, format_option]
    print("Using command: " + str(cmd))
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    #return namedtuple('Std', 'out, err')(process.stdout.read(), process.stderr.read())
    return process.returncode, stdout, stderr

code, out, err = getHashesMatchingGrep()
print('code = {}\nout = {}\nerr = {}'.format(code, out, err))

But all I get as output from this is:

Using command: ['git', 'log', '--all', '-i', "--grep='As Delivered'", '--format="%H"']
code = 0
out = b''
err = b''

I've also tried defining text=True, and shell=True for my Popen call. In this case I get 'None' from err, but still no other output. If I edit my function so that cmd=['git','log','--all'] I get something, but still, why won't it return anything when I add the --grep line? I know if I type the same git command (with grep) in the cmd terminal I get results.

Am I not understanding how subprocess is supposed to work? It seems to run OK, but if it is failing, why aren't I getting the stderr? I'm very confused, please help!

It appears I hadn't 'tokenized' my cmd array appropriately.
Before:

grep_option = '--grep=\'' + grepStr + '\''
format_option = '--format="' + '%H' + '"'
cmd = ['git', 'log', '--all', '-i', grep_option, format_option]

After:

format_option = '--format="' + '%H' + '"'
cmd = ['git', 'log', '--all', '-i', '--grep', grepStr, format_option]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM