返回标准输出内容的 subprocess.check_call 有什么好的等价物?
问题描述
我想要一个与 subprocess.check_call
的接口相匹配的好方法——即,它在失败时抛出 CalledProcessError
,是同步的,&c -- 但不是返回命令的返回码(如果它甚至这样做的话)返回程序的输出,要么只是标准输出,要么是(stdout,stderr)的元组.
I'd like a good method that matches the interface of subprocess.check_call
-- ie, it throws CalledProcessError
when it fails, is synchronous, &c -- but instead of returning the return code of the command (if it even does that) returns the program's output, either only stdout, or a tuple of (stdout, stderr).
有人有这样的方法吗?
解决方案
Python 2.7+
from subprocess import check_output as qx
Python 2.7
来自 subprocess.py:
import subprocess
def check_output(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd, output=output)
return output
class CalledProcessError(Exception):
def __init__(self, returncode, cmd, output=None):
self.returncode = returncode
self.cmd = cmd
self.output = output
def __str__(self):
return "Command '%s' returned non-zero exit status %d" % (
self.cmd, self.returncode)
# overwrite CalledProcessError due to `output` keyword might be not available
subprocess.CalledProcessError = CalledProcessError
另请参阅将系统命令输出捕获为字符串 另一个可能的 check_output()
实现示例.
See also Capturing system command output as a string for another example of possible check_output()
implementation.
相关文章