Sub topic 5
Checking exit codes and raising on failure
This chapter assumes you can run a command with subprocess.run, capture its output, and handle Python exceptions. It covers how to tell whether a child process succeeded and how to turn failure into an exception.
What an exit status is
Every process ends with an integer exit status. By convention, 0 means success and any other value means some kind of failure. The meaning of a specific non-zero value belongs to the program. Python reports the value as returncode on the CompletedProcess object that run returns.
import subprocess
import sys
result = subprocess.run([sys.executable, "-c", "import sys; sys.exit(2)"])
print(result.returncode)This prints 2. By default run does not complain about a non-zero status. It returns normally and leaves the check to you. A script that ignores returncode will continue as if the command had worked.
The sections below cover three ways to check the status:
- Test
returncodeyourself. - Pass
check=True. - Call
check_returncode()later.
Raising with check=True
Passing check=True makes run raise subprocess.CalledProcessError when the status is non-zero. This is the right default for commands that must succeed, because a failure cannot pass unnoticed.
import subprocess
import sys
code = "import sys; print('partial'); print('bad input', file=sys.stderr); sys.exit(4)"
try:
subprocess.run(
[sys.executable, "-c", code],
check=True,
capture_output=True,
text=True,
)
except subprocess.CalledProcessError as exc:
print("code:", exc.returncode)
print("stdout:", exc.stdout.strip())
print("stderr:", exc.stderr.strip())The exception carries the details of the failed run:
| Attribute | Contents |
|---|---|
| `returncode` | The exit status of the child |
| `cmd` | The command that was run, as you passed it |
| `stdout` | Captured standard output, or `None` if you did not capture it |
| `stderr` | Captured standard error, or `None` if you did not capture it |
| `output` | An alias for `stdout` |
The stdout and stderr attributes are only filled in when you asked run to capture them. Without capture_output=True (or stdout=PIPE), they are None. Calling .strip() on None then raises AttributeError, which hides the real error. When you plan to read the output in an except block, capture it in the call.
The default message from str(exc) names the command and the status, but it does not include stderr. Error messages are much more useful if you add it yourself.
import subprocess
import sys
def run_tool(args):
"""Run a command and return its stdout, or raise RuntimeError with its stderr."""
try:
completed = subprocess.run(
args,
check=True,
capture_output=True,
text=True,
)
except subprocess.CalledProcessError as exc:
raise RuntimeError(
f"{args[0]} failed with status {exc.returncode}: {exc.stderr.strip()}"
) from exc
return completed.stdout
print(run_tool([sys.executable, "-c", "print('fine')"]).strip())
try:
run_tool([sys.executable, "-c", "import sys; sys.exit('disk full')"])
except RuntimeError as err:
print(err)Passing a string to sys.exit prints it to stderr and sets the status to 1. The wrapper turns that into one exception with a readable message. from exc keeps the original exception attached for debugging.
Checking later with check_returncode
You do not have to decide about checking before the command runs. CompletedProcess.check_returncode() raises the same CalledProcessError if the status is non-zero, and does nothing otherwise.
import subprocess
import sys
result = subprocess.run([sys.executable, "-c", "import sys; sys.exit(1)"])
if result.returncode == 0:
print("ok")
else:
print("failed, deciding what to do")
try:
result.check_returncode()
except subprocess.CalledProcessError as exc:
print("raised with", exc.returncode)Use this form when some failures are acceptable and others are not. You can inspect the status, handle the cases you expect, and call check_returncode() for the rest.
When a non-zero status is not a failure
Many tools use the status to report a result, not only an error. grep and diff are common examples. grep returns 0 when it finds a match, 1 when it finds none, and 2 for a real error. diff returns 1 when files differ. If you run these with check=True, a normal "no match" answer becomes an exception.
For such tools, read the documentation, leave check off, and branch on returncode:
import subprocess
import sys
# A stand-in for a search tool: 0 = found, 1 = not found, 2 = error.
code = "import sys; sys.exit(1)"
result = subprocess.run([sys.executable, "-c", code])
if result.returncode == 0:
print("found")
elif result.returncode == 1:
print("not found")
else:
result.check_returncode()The final else branch matters. It makes unexpected statuses raise instead of being treated as "not found".
How the decision flows
A command that cannot start never reaches the exit-status check. Launch failures are a separate case, covered in the next chapter.
Negative return codes and other surprises
Death by signal
On POSIX systems (Linux and macOS), if the child is killed by a signal, returncode is the negative of the signal number. A status of -15 means the process received SIGTERM. A status of -9 means SIGKILL, which is what the operating system's out-of-memory killer sends.
import signal
import subprocess
import sys
code = "import os, signal; os.kill(os.getpid(), signal.SIGTERM)"
result = subprocess.run([sys.executable, "-c", code])
print(result.returncode)
if result.returncode < 0:
print("killed by", signal.Signals(-result.returncode).name)On Linux and macOS this prints -15 and killed by SIGTERM. Windows has no signals in this sense, so you will not see negative values there. check=True treats negative values as failures, because they are not 0.
Statuses are small numbers
On POSIX only the low 8 bits of the exit status are kept, so a program calling exit(256) reports 0. Do not design your own tools to return large values. Keep statuses in the range 0 to 255.
shell=True changes what you see
With shell=True, the child is a shell, and the shell reports the status of the command it ran. A missing command inside the shell does not raise FileNotFoundError. The shell exits with status 127 (POSIX) and prints a message to stderr. Without check=True this passes silently. Another reason to prefer argument lists is that failures show up as clear exceptions.
Pipelines hide failures
In a shell pipeline such as a | b, the status is normally that of the last command only. If a fails but b succeeds, the shell reports success. When you chain commands this way, check each process separately, or use a shell option such as set -o pipefail in bash.
Interactions with other options
- Timeouts. If you pass both
timeoutandcheck=True, a timeout raisesTimeoutExpiredfirst. The status check never runs because the child was killed before it finished normally. - Exception hierarchy.
CalledProcessErrorandTimeoutExpiredboth inherit fromsubprocess.SubprocessError. Catching that base class handles both. It does not catchFileNotFoundError, which is anOSError. Popen. The lower-levelPopenclass has nocheckoption. You readproc.returncodeafterwait()orcommunicate()and raise on your own.
Exercise
A script runs subprocess.run(["diff", "a.txt", "b.txt"], check=True) to compare two files. It crashes with CalledProcessError even though both files exist and diff worked correctly. Why does this happen, and how would you rewrite the call so it distinguishes "files differ" from a real error?
Show answer
diff exits with 0 when the files are identical, 1 when they differ, and 2 or more when something went wrong. check=True treats the 1 as a failure, so a normal "files differ" result raises the exception. Remove check=True, run with captureoutput=True and text=True, then branch on returncode: 0 means identical, 1 means different (use stdout for the differences), and any other value means a real error, which you can raise with result.checkreturncode().