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.
os.system
. Briefly, there is no way to do that;os.system
runs a command completely outside of Python's control, and simply returns its exit code (zero for success, 1-255 for failure). The proper solution is to switch tosubprocess.run()
and friends, where you get this control. (There are several old questions with accepted answers which suggestos.popen()
but that was the wrong answer for a long time, and now simply an obscure wrapper which callssubprocess
anyway.) – tripleeecheck_call()
does not run shell unless you explicitly ask it. – jfs