簡體   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