Skip to main content

Build CLIs with `argparse`

Standard Library

argparse CLI Toolkit

Create user-friendly command-line interfaces without third-party dependencies.

Skeleton

import argparse

parser = argparse.ArgumentParser(description='Process invoices.')
parser.add_argument('--customer', required=True)
parser.add_argument('--limit', type=int, default=10)
args = parser.parse_args()
  • type= performs casting.
  • choices= restricts values.
  • action='store_true' toggles booleans.

Subcommands

subparsers = parser.add_subparsers(dest='command', required=True)

sync_parser = subparsers.add_parser('sync')
sync_parser.add_argument('--full', action='store_true')
  • Each parser gets its own options and help text.
  • Use dest to inspect which command the user invoked.

Tips

  • Provide examples in parser.epilog for better --help.
  • Pair argparse with pathlib and datetime to validate inputs.
  • Exit gracefully on errors (argparse does this automatically).

Next up in your learning path