Sub topic 10
Reporting errors and choosing exit codes
This chapter assumes you can write a parser with add_argument, that you know what main(argv) is for, and that you can read a Python traceback. Here you decide what the program does when something goes wrong. That means where the message goes, what status the process returns, and which failures get their own code.
What the caller sees
A command-line program reports results through three channels:
- stdout carries the program's normal output, which another program may read.
- stderr carries diagnostics and error messages. A pipe such as
tool | sortdoes not capture it. - The exit status is an integer the shell stores in
$?.0means success. Any other value means failure.
Scripts, make, CI systems and && chains look only at the exit status. A tool that prints "error" but exits 0 looks successful to all of them. A tool that exits 1 after printing nothing leaves the user guessing. Do both parts: write a clear message to stderr and return a non-zero status.
On POSIX systems the status is truncated to 0–255. sys.exit(256) therefore looks like 0 to the shell. Keep your codes small.
Errors argparse reports for you
parse_args handles malformed input itself. A missing required argument, an unknown option, a failed type conversion and a value outside choices all follow the same path. argparse calls parser.error(message), which prints the usage line and a message to stderr, then exits with status 2.
import argparse
parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("--n", type=int)
try:
parser.parse_args(["--n", "x"])
except SystemExit as exc:
print("exit code:", exc.code)The program prints this to stderr:
usage: demo [-h] [--n N]
demo: error: argument --n: invalid int value: 'x'It then prints exit code: 2 to stdout. The exit is an ordinary SystemExit exception, so you can catch it. Tests rely on this, as the testing chapter shows.
Two related methods are worth knowing:
parser.error(message)prints usage, printsprog: error: messageto stderr and exits with status 2.parser.exit(status=0, message=None)exits with the status you choose. If you pass a message, it goes to stderr.
Python 3.9 added ArgumentParser(exit_on_error=False), which makes some conversion failures raise ArgumentError instead. In several Python versions it does not cover every error, such as missing required arguments, so those still exit. For code that must work across versions, catch SystemExit or subclass ArgumentParser and override error.
Validating combinations with parser.error
A type function checks one value at a time. Rules that involve several arguments, such as "--max must not be smaller than --min", can only be checked after parsing. Report them with parser.error so they look like every other usage mistake and exit with the same status 2.
Raise argparse.ArgumentTypeError inside a type function, as the validation chapter showed, when one value is bad. Call parser.error when the combination is bad.
Reporting runtime errors
Some failures are not usage mistakes. The arguments are valid, but a file is missing, the disk is full or the network is down. Handle these in main, not in the parser:
- Catch the specific exceptions you expect, such as
OSError. - Print a one-line message to stderr, prefixed with the program name.
- Return a non-zero status instead of letting a traceback escape.
Here is a complete tool that counts lines in files and keeps going when one file fails:
import argparse
import sys
from pathlib import Path
EXIT_OK = 0
EXIT_ERROR = 1
def build_parser():
parser = argparse.ArgumentParser(prog="countlines",
description="Count lines in text files.")
parser.add_argument("paths", nargs="+", type=Path, help="files to count")
parser.add_argument("--min", type=int, default=0, dest="minimum",
help="only show files with at least this many lines")
parser.add_argument("--max", type=int, default=None, dest="maximum",
help="only show files with at most this many lines")
return parser
def parse_args(argv=None):
parser = build_parser()
args = parser.parse_args(argv)
if args.maximum is not None and args.maximum < args.minimum:
parser.error("--max must not be smaller than --min")
return args
def count_lines(path):
with path.open("r", encoding="utf-8") as handle:
return sum(1 for _ in handle)
def main(argv=None):
args = parse_args(argv)
failures = 0
for path in args.paths:
try:
total = count_lines(path)
except OSError as exc:
print(f"countlines: {path}: {exc.strerror or exc}", file=sys.stderr)
failures += 1
continue
except UnicodeDecodeError:
print(f"countlines: {path}: not valid UTF-8 text", file=sys.stderr)
failures += 1
continue
if total < args.minimum:
continue
if args.maximum is not None and total > args.maximum:
continue
print(f"{total} {path}")
return EXIT_ERROR if failures else EXIT_OK
if __name__ == "__main__":
try:
code = main()
except KeyboardInterrupt:
print(file=sys.stderr)
code = 130
raise SystemExit(code)Suppose notes.txt has three lines and missing.txt does not exist:
$ python countlines.py notes.txt missing.txt; echo "exit: $?"
3 notes.txt
countlines: missing.txt: No such file or directory
exit: 1
$ python countlines.py notes.txt --min 5 --max 2; echo "exit: $?"
usage: countlines [-h] [--min MINIMUM] [--max MAXIMUM] paths [paths ...]
countlines: error: --max must not be smaller than --min
exit: 2The first run processes both paths. The good one reaches stdout and the bad one reaches stderr. The final status says that something failed. Stopping at the first failure would hide the other problems, so the loop counts failures and decides the status at the end.
Two details are easy to miss. UnicodeDecodeError is a subclass of ValueError, not OSError, so it needs its own except clause. exc.strerror can be None for some OSError instances, so the code falls back to the exception itself.
Choosing exit codes
Some values already have a meaning, so reuse them and avoid contradicting them:
| Code | Meaning | Source |
|---|---|---|
| 0 | Success | Universal |
| 1 | General failure | Convention |
| 2 | Usage error | argparse and many Unix tools |
| 126 | Command found but not executable | Shell |
| 127 | Command not found | Shell |
| 128 + N | Killed by signal N | Shell |
| 130 | Interrupted by Ctrl-C (128 + SIGINT 2) | Shell convention |
For most tools, 0, 1 and argparse's 2 are enough. Add your own codes only when a caller needs to react differently to different failures. For example, a deploy script might retry on "network unreachable" but stop on "configuration invalid". Keep these rules when you add them:
- Stay between 3 and 125, and avoid values the shell uses.
- Name them as constants, such as
EXIT_NETWORK = 3. - Document them in the
epilogof the help text or in the README. - Do not use a different code for every possible error. Callers cannot act on dozens of them.
Some tools give a normal result a non-zero status on purpose. grep exits 1 when nothing matches, and diff exits 1 when files differ. If you copy that pattern, document it. Otherwise set -e scripts will treat a valid answer as a crash.
How the status leaves the program
main returns an integer and the __main__ block passes it to SystemExit. Python treats the argument like this:
Noneor0exits with status 0. Amainthat forgets to return therefore reports success.- Another integer becomes the exit status.
- Any other object, such as a string, is printed to stderr and the status is 1.
The string form means sys.exit("config file not found") is a quick way to report a fatal error. In a testable main, though, prefer print(..., file=sys.stderr) followed by return, so the caller and the tests see a normal return value.
Interrupts
Pressing Ctrl-C raises KeyboardInterrupt, which is not a subclass of Exception. A bare except Exception therefore will not catch it, and without a handler the user sees a traceback. The __main__ block above catches it, prints a newline so the shell prompt starts on a clean line, and exits with 130. This matches what the shell reports for a process killed by SIGINT. The handler sits outside main, so tests can call main without it.
Exercise
A tool is run as backup --dest /mnt/usb data/. The arguments parse correctly, but /mnt/usb is not mounted and main catches the resulting OSError. What should the tool print, where should it print it, and what should it return? Would parser.error be the right call?
Show answer
It should print one line such as "backup: /mnt/usb: No such file or directory" to stderr and return a non-zero status, normally 1, or a documented custom code if callers need to detect this case. parser.error is the wrong call. It prints usage and exits with status 2, which signals a mistake in how the command was typed. Here the command was valid and the environment failed.
Exercise
A script contains ./countlines.py report.txt && echo done. The file report.txt does not exist and main returns None after printing the error message. What does the user see, and why is that a bug?
Show answer
The error message appears and then "done" is printed, because None becomes exit status 0 and && treats that as success. The fix is to return a non-zero status, for example return 1, after reporting the error.