Sub topic 10
Reporting errors and choosing exit codes
This chapter assumes you can build a parser with add_argument and that your program has a main(argv) function that returns an integer.
Exit codes are the contract
When a program ends, it hands its caller a small integer called the exit code. Shells, make, CI systems and other scripts read it to decide whether the run worked. Zero means success. Any other value means failure.
| Code | Meaning | Who produces it |
|---|---|---|
| 0 | Success | Your `main` |
| 1 | General runtime failure | Your `main` |
| 2 | Usage error (bad command line) | `argparse` |
| 130 | Interrupted with Ctrl+C | Shell convention (128 + SIGINT) |
Pick a few more codes only when callers need to tell failures apart. Document them in the epilog.
What argparse does for you
When parse_args finds a missing argument, an unknown option, a failed type conversion or a value outside choices, it calls parser.error(message). That method prints the usage line and the message to stderr, then exits with status 2. Your code never sees the bad input.
You can call parser.error yourself for checks that argparse cannot express, such as rules that involve two arguments. The user then gets the same format and the same exit code 2 as for any other usage mistake.
Reporting runtime failures
A runtime failure is a problem with the environment, not the command line: a missing file, a refused connection, a permission error. Catch the expected exceptions in main. Print a one-line message to stderr, and return a nonzero code. A traceback is for bugs in your program, not for a user who mistyped a path.
import argparse
import sys
def build_parser():
parser = argparse.ArgumentParser(
prog="linecount",
description="Count the lines in a file.",
epilog="exit codes: 0 ok, 1 unreadable file, 2 usage error, 3 too few lines",
)
parser.add_argument("path", help="file to read")
parser.add_argument("--min", type=int, default=0,
help="fail if the file has fewer lines than this")
return parser
def main(argv=None):
parser = build_parser()
args = parser.parse_args(argv)
if args.min < 0:
parser.error("--min must not be negative")
try:
with open(args.path, encoding="utf-8") as handle:
count = sum(1 for _ in handle)
except OSError as exc:
print(f"linecount: cannot read {args.path}: {exc.strerror}", file=sys.stderr)
return 1
print(count)
if count < args.min:
print(f"linecount: expected at least {args.min} lines", file=sys.stderr)
return 3
return 0
if __name__ == "__main__":
raise SystemExit(main())The result goes to stdout and the diagnostics go to stderr. A caller can then run linecount data.txt > total.txt and still see the errors on the terminal.
Common mistakes
- Printing errors with
print(...)to stdout, which mixes them into data that another program may be reading. - Returning 0 after printing an error message, so scripts think the run succeeded.
- Calling
sys.exitdeep inside helper functions. Raise an exception or return a value, and letmaindecide the code. - Catching
Exceptionbroadly, which hides real bugs behind a friendly message.
Exercise
A script runs linecount missing.txt and the file does not exist. What exit code does it get, and which stream receives the message? Why is the code not 2?
Show answer
Exit code 1, and the message goes to stderr. Code 2 is reserved for usage errors, meaning the command line was malformed. Here the command line was valid and the failure came from the environment, so main reports it as a general runtime failure.