我正在尝试从git add
命令获取消息,以便稍后打印到日志文件。
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()
捕获错误消息?
答案 0 :(得分:8)
来自subprocess.check_output()
的文件:
当出现错误情况时,如果返回码非零,则会引发
CalledProcessError
。CalledProcessError
对象将包含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