I want to capture the stdout
stream of a shell command in a python (3) script, and being able, at the same time, to check the return code of the shell command i
To get both the process output and the returned code:
from subprocess import Popen, PIPE
p = Popen(["ls", "non existent"], stdout=PIPE)
output = p.communicate()[0]
print(p.returncode)
subprocess.CalledProcessError
is a class. To access returncode
use the exception instance:
from subprocess import CalledProcessError, check_output
try:
output = check_output(["ls", "non existent"])
returncode = 0
except CalledProcessError as e:
output = e.output
returncode = e.returncode
print(returncode)