Argparse Subcommands For CLIs
Structure a CLI with argparse subparsers so each verb owns its flags and help text, and the top level stays a clean verb list.
Code
import argparse
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog='ledger', description='Mini ledger CLI')
sub = parser.add_subparsers(dest='command', required=True)
add = sub.add_parser('add', help='record an entry')
add.add_argument('amount', type=int)
add.add_argument('--memo', default='')
report = sub.add_parser('report', help='summarize entries')
report.add_argument('--since', default=None)
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
if args.command == 'add':
print(f'recorded {args.amount} ({args.memo or "no memo"})')
return 0
if args.command == 'report':
print(f'report since={args.since or "beginning"}')
return 0
return 2
if __name__ == '__main__':
raise SystemExit(main(['add', '250', '--memo', 'coffee']))Output
Captured from a sandboxed run of this snippet in the build pipeline.
recorded 250 (coffee)How it works
One way to read it: the functions build_parser and main, doing all the work.
When the guard condition holds, SystemExit is thrown rather than a bogus value returned.
What to watch for
- Requires
argparseas a package; the snippet will not run without it. - The guard
__name__ == '__main__'short-circuits the flow with an earlyraisewhen its condition holds.
Putting it to use
Entry signature: def build_parser() -> argparse.ArgumentParser
Running the file prints labeled results such as recorded, report since= — each operation’s effect is visible in the output.
The entry point wires build_parser together — run it once and the whole demo flows.
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Is there a failure path for bad input?
- The code refuses to continue: `SystemExit` is thrown while the state is still recoverable.
- What does Argparse Subcommands For CLIs print when run?
- Run it as a complete program — the output lines carry labels such as `recorded`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.