CLI planner project (5/6): argparse and the command line

Subcommands add, list, and remove, date arguments, exit codes, and messages on stderr. Twelve exercises for an argparse planner CLI.

Illustration : mains tapant dans un terminal sombre sur un ordinateur portable, calendrier mural en arrière-plan

AI-generated illustration

Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.

argparse structures the CLI with ArgumentParser and add_subparsers for agenda add, agenda list, and agenda remove. Each subcommand has its own arguments: --title, --start (an ISO string), --from / --to for the list, --id for deletion. Return sys.exit(1) on a user error or a corrupt file.

Previous chapter: tests with pytest.

Good practice

  • A clear prog and description on the main parser.
  • Error messages on stderr (print(..., file=sys.stderr)).
  • type= to parse dates with a small function that calls datetime.fromisoformat.

Exercises (12)

Exercise 1 — Create a parser with an add subcommand and a --title argument. Easy

Show the solution
import argparse
p = argparse.ArgumentParser()
sub = p.add_subparsers(required=True)
add = sub.add_parser("add")
add.add_argument("--title", required=True)

Exercise 2 — Parse the fake argv ["list", "--from", "2026-01-01T00:00:00"]. Intermediate

Show the solution
args = p.parse_args(["list", "--from", "2026-01-01T00:00:00"])

Exercise 3 — A main() function that returns an integer code, and sys.exit(main()) in __main__.py. Easy

Show the solution
def main() -> int:
    ...
    return 0

if name == “main”: raise SystemExit(main())

Exercise 4 — ArgumentDefaultsHelpFormatter so the help text shows defaults. Intermediate

Show the solution
argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)

Exercise 5 — A global try/except in main so ValueError becomes a message and exit code 2. Intermediate

Show the solution
try:
    ...
except ValueError as e:
    print(e, file=sys.stderr)
    return 2

Exercise 6 — Why separate parse_args from running the service (testability)? Easy

Show the solution
# You can test dispatch(args) with a namespace built by hand.

Exercise 7 — A global --file option for the JSON path (parent parser). Hard

Show the solution
p.add_argument("--file", type=Path, default=None)

Exercise 8 — A simple table using aligned str.format or f-strings. Intermediate

Show the solution
for e in events:
    print(f"{e.start:%Y-%m-%d %H:%M}  {e.title}")

Exercise 9 — Automatic --help: check that it mentions the subcommands. Easy

Show the solution
python -m agenda_cli --help

Exercise 10 — Reading stdin is not required in v1 — a note for v2. Easy

Show the solution
Import events from CSV or JSON on stdin.

Exercise 11 — Avoid print in the service: pass results up to the CLI layer. Hard

Show the solution
# The service returns list[Event]; cli formats it — service tests without capturing stdout.

Exercise 12 — argparse vs click: one advantage of each. Intermediate

Show the solution
argparse: stdlib; click: ergonomics, colors, testing with CliRunner.

Next

Shipping and extensions

Amazon

Amazon.ca

Further reading

Was this page helpful?

Have a question about this guide or need advice? Ask us here

Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.