Python · Chapter 42 of 45

argparse — CLI arguments

The `argparse` module builds command-line interfaces: it parses `sys.argv`, generates `--help` and validates types.

Add arguments with `parser.add_argument(...)` and read the result from `parser.parse_args()`.

Positional vs optional

`add_argument('name')` is positional (required). `add_argument('--verbose')` is optional.

Types & choices

`type=int` casts, `choices=[...]` restricts values, `default=X` provides fallback.

Example 1 (python)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
parser.add_argument("--times", type=int, default=1)
args = parser.parse_args(["Ana", "--times", "3"])
print(f"Hi {args.name}! " * args.times)
Output
Hi Ana! Hi Ana! Hi Ana! 

Parse a positional 'name' and optional '--times'.

Example 2 (python)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--mode", choices=["dev","prod"], default="dev")
args = parser.parse_args(["--mode", "prod"])
print(args.mode)
Output
prod

Restrict values with choices.

Key points

  • `argparse` is in the standard library.
  • Positional args: required.
  • Optional args: start with `--`.
  • Automatic `--help` for free.
💡 Note: For fancier CLIs consider `click` or `typer` — they build on argparse but require less boilerplate.

📝 Quick Quiz

1. Which is a positional argument?

2. Argparse auto-generates:

3. `type=int` in add_argument: