Python Glossary Русский

all Python 3Exceptionsexception

subprocess.CalledProcessError

module exceptions

Raised when a child process exits with a non-zero status and the call asked for that check (run with check=True, check_call, check_output).

Syntax

except subprocess.CalledProcessError as e:  # e.returncode, e.cmd, e.stdout, e.stderr

Only the checking calls raise it: run() without check=True, call() and Popen just hand back the non-zero code as a number. The stdout and stderr attributes are filled only when output was captured (capture_output=True or check_output); otherwise they are None and the reason for the failure is lost. It is not an OSError: a missing program raises FileNotFoundError, which except CalledProcessError does not catch.

Examples

import subprocess, sys
code = 'import sys; sys.stderr.write("нет файла"); sys.exit(3)'
try:
    subprocess.run([sys.executable, '-c', code], check=True,
                   capture_output=True, text=True)
except subprocess.CalledProcessError as e:
    print(e.returncode)  # → 3
    print(e.stderr)  # → нет файла
import subprocess, sys
cmd = [sys.executable, '-c', 'import sys; sys.exit(2)']
r = subprocess.run(cmd)  # без check исключения нет
print(r.returncode)  # → 2

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy