Sub topic 5
Checking exit codes and raising on failure
This chapter assumes you can call subprocess.run, capture output as text, and handle Python exceptions. It covers how to tell whether a command succeeded and how to make failure raise an error.
What an exit code means
Every process ends with an integer called its exit status, or return code. By convention, 0 means success and any other value means failure. The meaning of a non-zero value depends on the program. Many programs use 1 for a general error and 2 for bad usage.
subprocess.run does not treat a non-zero exit code as an error by default. It returns normally, and you read the code from CompletedProcess.returncode.
import subprocess
import sys
result = subprocess.run([sys.executable, "-c", "import sys; sys.exit(3)"])
print(result.returncode)
if result.returncode != 0:
print("the command failed")This prints 3 and then the failure message. If you never check returncode, a failing command goes unnoticed and your program continues as if nothing happened.
Raising on failure with check=True
Pass check=True and run raises subprocess.CalledProcessError whenever the exit code is non-zero. The exception carries the details you need to report the problem.
import subprocess
import sys
try:
subprocess.run(
[sys.executable, "-c", "import sys; sys.exit(3)"],
check=True,
)
except subprocess.CalledProcessError as exc:
print("command failed with code", exc.returncode)The exception has these attributes:
| Attribute | Contents |
|---|---|
| `returncode` | The exit status of the child |
| `cmd` | The command that was run |
| `stdout` | Captured standard output, or `None` if not captured |
| `stderr` | Captured standard error, or `None` if not captured |
Prefer check=True for any command whose failure should stop the current task. It turns a silent problem into a visible one.
Reading the error output
When you combine check=True with capture_output=True, the exception holds what the child wrote. This is usually the most useful information for a log message.
import subprocess
import sys
code = "import sys; print('partial'); sys.stderr.write('disk full\\n'); sys.exit(2)"
try:
subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True,
check=True,
)
except subprocess.CalledProcessError as exc:
print("exit code:", exc.returncode)
print("stdout:", exc.stdout.strip())
print("stderr:", exc.stderr.strip())Without capture_output=True, exc.stderr is None and calling .strip() on it would fail. The child's output would instead go straight to your terminal.
Checking later with check_returncode
You can run a command without check=True, inspect the result, and raise afterwards. CompletedProcess.check_returncode() raises the same CalledProcessError if the code is non-zero.
import subprocess
import sys
result = subprocess.run([sys.executable, "-c", "import sys; sys.exit(1)"])
if result.returncode == 1:
print("expected a warning code, continuing")
else:
result.check_returncode()This pattern fits programs that use several exit codes. For example, grep returns 0 when it finds a match, 1 when it finds none, and 2 on a real error. Treating 1 as an error there would be wrong.
Common mistakes
- Forgetting
check=Trueand assuming a failed command raises. It does not. - Reading
exc.stderrwhen output was not captured. The value isNone. - Treating every non-zero code as the same problem. Read the program's documentation.
- Confusing a failed command with a command that could not start. A missing program raises
FileNotFoundError, notCalledProcessError. The next chapter covers that case.
Exercise
A script runs subprocess.run(["grep", "foo", "data.txt"], check=True). The file exists but does not contain "foo". What happens, and how would you change the code to treat "no match" as normal while still failing on real errors?
Show answer
grep exits with code 1 when nothing matches, so check=True raises CalledProcessError. Remove check=True, run the command, and inspect returncode. Accept 0 (match) and 1 (no match), and call result.check_returncode() or raise an error for any other code, such as 2.