繁体   English   中英

使用子进程捕获 git 命令 output

[英]Capturing git command output with subprocess

我正在尝试为提交消息中包含“交付时”的提交返回所有 git 提交哈希。 本质上,我想捕获以下 git 命令的 output:

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

上面的 git 命令按我预期的方式在命令行中运行,每 output 行返回一个匹配的 hash。 这是我试图用来实现我的目标的代码:

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))

但我从中得到的 output 是:

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

我还尝试为我的 Popen 调用定义 text=True 和 shell=True。 在这种情况下,我从错误中得到“无”,但仍然没有其他 output。如果我编辑我的 function 以便 cmd=['git','log','--all'] 我得到了一些东西,但仍然,为什么赢了当我添加 --grep 行时它返回任何内容吗? 我知道如果我在 cmd 终端中键入相同的 git 命令(使用 grep),我会得到结果。

我不明白子流程应该如何工作吗? 它似乎运行正常,但如果它失败了,为什么我没有得到 stderr? 我很困惑,请帮忙!

看来我没有适当地“标记化”我的 cmd 数组。
前:

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

后:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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