无法从 (Python) subprocess.check_output() 获取 stdout/stderr

Can't get stdout/stderr from (Python) subprocess.check_output()

我正在尝试从 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() 捕获错误消息?

来自 subprocess.check_output() 的文档:

If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.

git add returns 出现错误情况时的非零退出代码。捕获那个异常,你的输出就在那里:

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;相反,将您的参数作为 list 传递,它们将在没有中介 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