返回标准输出内容的 subprocess.check_call 有什么好的等价物?

What#39;s a good equivalent to subprocess.check_call that returns the contents of stdout?(返回标准输出内容的 subprocess.check_call 有什么好的等价物?)

本文介绍了返回标准输出内容的 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.

这篇关于返回标准输出内容的 subprocess.check_call 有什么好的等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:返回标准输出内容的 subprocess.check_call 有什么好的等价物?

基础教程推荐