What's a good equivalent to python's subprocess.check_call that returns the contents of stdout?
Question: 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?


Answer: ### Python 2.7+

    
    
    from subprocess import check_output as qx
    

### Python < 2.7

From [subprocess.py](http://hg.python.org/cpython/file/2.7/Lib/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](http://stackoverflow.com/questions/236737/capturing-system-command-
output-as-a-string/236909#236909) for another example of possible
`check_output()` implementation.

