2016-08-12 88 views
2

我試圖從git add命令中獲取消息,以便日後打印到日誌文件。無法從(Python)subprocess.check_output()獲取stdout/stderr()

import subprocess 
import os 

filename = 'test.txt' 

# Add changes 
add_cmd = """git add "%s" """ % filename 
os.system(add_cmd) 
a = subprocess.check_output(add_cmd, shell=True, stderr=subprocess.STDOUT) 

os.system()呼叫顯示屏幕:

fatal: Not a git repository (or any of the parent directories): .git 

這是正確的,因爲這個文件夾是不是一個git回購。

subprocess.check_output()調用失敗:

File "test.py", line 11, in <module> 
    a = subprocess.check_output(add_cmd, shell=True, stderr=subprocess.STDOUT) 
    File "/usr/lib/python2.7/subprocess.py", line 573, in check_output 
    raise CalledProcessError(retcode, cmd, output=output) 
subprocess.CalledProcessError: Command 'git add "test.txt" ' returned non-zero exit status 128 

爲什麼我不能夠捕獲錯誤消息subprocess.check_output()

回答

7

從documenation爲subprocess.check_output()

如果返回代碼爲非零它提出了一個CalledProcessErrorCalledProcessError對象將具有returncode屬性中的返回碼和output屬性中的任何輸出。

git add當出現錯誤條件時返回非零退出代碼。捕獲了異常,你的輸出有:

try: 
    a = subprocess.check_output(add_cmd, shell=True, stderr=subprocess.STDOUT) 
except subprocess.CalledProcessError as cpe: 
    print cpe.output 

演示:

>>> import subprocess 
>>> import os 
>>> filename = 'test.txt' 
>>> add_cmd = """git add "%s" """ % filename 
>>> try: 
...  a = subprocess.check_output(add_cmd, shell=True, stderr=subprocess.STDOUT) 
... except subprocess.CalledProcessError as cpe: 
...  print cpe.output 
... 
fatal: Not a git repository (or any of the parent directories): .git 

>>> cpe.returncode 
128 

你可能不需要使用shell=True;代之以將列表作爲參數傳入,並且它們將在沒有中介shell的情況下執行。這有額外的好處,你不必擔心妥善逃跑filename

add_cmd = ['git', 'add', filename] 
try: 
    a = subprocess.check_output(add_cmd, stderr=subprocess.STDOUT) 
except subprocess.CalledProcessError as cpe: 
    print cpe.output