What's a good equivalent to python's subprocess.check

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

Does somebody have a method that does this?


Python 2.7+

from subprocess import check_output as qx

Python < 2.7

From 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

See also Capturing system command output as a string for another example of possible check_output() implementation.


I can not get formatting in a comment, so this is in response to JF Sebastian's answer

I found this very helpful so I figured I would add to this answer. I wanted to be able to work seamlessly in the code without checking the version. This is what I did...

I put the code above into a file called 'subprocess_compat.py'. Then in the code where I use subprocess I did.

import sys
if sys.version_info < (2, 7):
    import subprocess_compat
    subprocess.check_output = subprocess_compat.check_output

Now anywhere in the code I can just call 'subprocess.check_output' with the params I want and it will work regardless of which version of python I am using.


该函数以字符串列表的形式返回终端输出。

import subprocess,sys
def output(cmd):
    cmd_l = cmd.split()
    output = subprocess.Popen(cmd_l, stdout=subprocess.PIPE).communicate()[0]
    output = output.decode("utf-8")
    return (output)
链接地址: http://www.djcxy.com/p/25326.html

上一篇: 将几个子过程连接在一起

下一篇: 什么是与Python的subprocess.check等效