Sub topic 3
Reporting Errors and Choosing Exit Codes
Assume you know basic ArgumentParser usage and can write Python functions, pytest tests, and a pyproject.toml file.
Reporting Errors and Choosing Exit Codes
argparse reports invalid command-line input by printing usage information and an error to standard error. It then raises SystemExit with code 2.
Use other nonzero codes for failures after parsing, such as a missing input file. Return 0 for success. Keep parsing and application work separate so tests can call main(argv) directly.
import argparse
import sys
def main(argv=None):
parser = argparse.ArgumentParser(prog="convert")
parser.add_argument("source")
args = parser.parse_args(argv)
try:
with open(args.source) as file:
print(file.read())
except OSError as error:
print(f"convert: {error}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())Argument Groups and Mutually Exclusive Options
Argument groups organize help output. A mutually exclusive group also prevents conflicting options:
group = parser.add_mutually_exclusive_group()
group.add_argument("--quiet", action="store_true")
group.add_argument("--verbose", action="store_true")Passing both options produces an argparse error and exit code 2.
Building Tools with Subcommands
Subcommands give one program several related operations. Create a parser for each command and store its handler with set_defaults:
import argparse
def add(args):
print(f"adding {args.item}")
return 0
def list_items(args):
print("listing", "all" if args.all else "open", "items")
return 0
parser = argparse.ArgumentParser(prog="todo")
commands = parser.add_subparsers(dest="command", required=True)
add_parser = commands.add_parser("add")
add_parser.add_argument("item")
add_parser.set_defaults(func=add)
list_parser = commands.add_parser("list")
list_parser.add_argument("--all", action="store_true")
list_parser.set_defaults(func=list_items)
args = parser.parse_args()
raise SystemExit(args.func(args))Testing, Packaging, and Reuse
Pass an explicit list to main in pytest. Capture output with capsys, and use pytest.raises(SystemExit) for invalid arguments. Check both the exit code and the error stream.
To install a console command, add an entry point:
[project.scripts]
todo = "todo:main"A parent parser shares common options between subcommands. Build it with add_help=False, then pass it through parents=[common]. This avoids copying declarations, but changes affect every child parser.
Choosing argparse
argparse is enough for small and medium tools, needs no dependency, and gives standard help and error behavior. Consider Click or Typer when you need decorator-based commands, richer prompts, or larger command trees. Choose based on team familiarity and dependency policy.
Exercise
What exit code does argparse normally use for invalid command-line input?
Show answer
It raises SystemExit with exit code 2.