Skip to content

Python subprocess: CalledProcessError on a non-zero exit code

Python & Gotested on Python 3.14.2, uv 0.9.26

A system command called from Python fails, and instead of carrying on silently, subprocess.run raises an exception. That is the point of check=True: no silent continuation after an error.

Symptom

r = subprocess.run(["ls", "/gibt-es-nicht"], capture_output=True, text=True)
print(r.returncode, r.stderr.strip())
try:
    subprocess.run(["false"], check=True)
except subprocess.CalledProcessError as err:
    print("CalledProcessError, returncode", err.returncode)
1 ls: /gibt-es-nicht: No such file or directory
CalledProcessError, returncode 1

Without check=True there is only returncode 1 and the message in stderr. With check=True the exception is raised.

Diagnosis

Read returncode and stderr – capture_output=True and text=True make stderr available as a string.

r = subprocess.run(["ls", "/gibt-es-nicht"], capture_output=True, text=True)
print(r.returncode, r.stderr.strip())
1 ls: /gibt-es-nicht: No such file or directory

Causes

check=TrueThe exit code becomes an exception

With check=True, subprocess.run checks the exit code itself and raises CalledProcessError as soon as it is not 0.

returncode 1The command really failed

The reason is in the called program's stderr – here the file does not exist.

Fix

Catch the error at the boundary and translate it with raise … from err into your own, readable error; the traceback then shows both errors.

Don't: Drop check=True to avoid the exception and then not check returncode.

▶
Break it yourself and find it – free
Python hands-on, Day 3: the CLI tool tidy with Typer, pathlib and safe subprocess calls.
Go to day 3 →

FAQ

How do I see the program's error message?

With capture_output=True and text=True it is a string in stderr – on the exception in err.stderr.

Is shell=True an alternative?

No. A list of arguments without a shell is safer because no shell interprets special characters.

Related error patterns

More