Check a command's return code when subprocess raises a CalledProcessError exception Check a command's return code when subprocess raises a CalledProcessError exception python-3.x python-3.x

Check a command's return code when subprocess raises a CalledProcessError exception


To get both the process output and the returned code:

from subprocess import Popen, PIPEp = 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_outputtry:    output = check_output(["ls", "non existent"])    returncode = 0except CalledProcessError as e:    output = e.output    returncode = e.returncodeprint(returncode)


Most likely my answer is no longer relevant, but I think it may be solved with this code:

import subprocessfailing_command='ls non_existent_dir'try:    subprocess.check_output(failing_command, shell=True, stderr=subprocess.STDOUT)except subprocess.CalledProcessError as e:    ret =   e.returncode     if ret in (1, 2):        print("the command failed")    elif ret in (3, 4, 5):        print("the command failed very much")