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

I'm trying to get the message from a git add command, to print to a log file later on.

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)

The os.system() call shows in screen:

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

which is correct, since this folder is not a git repo.

But the subprocess.check_output() call fails with:

File "test.py", line 11, in

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

Why am I not able to catch the error message with subprocess.check_output()?

解决方案

From the documenation for 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 a non-zero exit code when there is an error condition. Catch that exception, your output is there:

try:

a = subprocess.check_output(add_cmd, shell=True, stderr=subprocess.STDOUT)

except subprocess.CalledProcessError as cpe:

print cpe.output

Demo:

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

You probably don't need to use shell=True; pass in your arguments as a list instead and they'll be executed without an intermediary shell. This has the added advantage you don't need to worry about properly escaping filename:

add_cmd = ['git', 'add', filename]

try:

a = subprocess.check_output(add_cmd, stderr=subprocess.STDOUT)

except subprocess.CalledProcessError as cpe:

print cpe.output

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值