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.

PythonCli Tooling

Code

pythonsnippet
31 lines
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 argparse as a package; the snippet will not run without it.
  • The guard __name__ == '__main__' short-circuits the flow with an early raise when 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

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`.