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.
Getting started
Home Assistant
Buying
Subcommands add, list, and remove, date arguments, exit codes, and messages on stderr. Twelve exercises for an argparse planner CLI.


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.
prog and description on the main parser.stderr (print(..., file=sys.stderr)).type= to parse dates with a small function that calls datetime.fromisoformat.Exercise 1 — Create a parser with an add subcommand and a --title argument. Easy
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
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
def main() -> int: ... return 0
if name == “main”: raise SystemExit(main())
Exercise 4 — ArgumentDefaultsHelpFormatter so the help text shows defaults. Intermediate
argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
Exercise 5 — A global try/except in main so ValueError becomes a message and exit code 2. Intermediate
try:
...
except ValueError as e:
print(e, file=sys.stderr)
return 2
Exercise 6 — Why separate parse_args from running the service (testability)? Easy
# You can test dispatch(args) with a namespace built by hand.
Exercise 7 — A global --file option for the JSON path (parent parser). Hard
p.add_argument("--file", type=Path, default=None)
Exercise 8 — A simple table using aligned str.format or f-strings. Intermediate
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
python -m agenda_cli --help
Exercise 10 — Reading stdin is not required in v1 — a note for v2. Easy
Import events from CSV or JSON on stdin.
Exercise 11 — Avoid print in the service: pass results up to the CLI layer. Hard
# The service returns list[Event]; cli formats it — service tests without capturing stdout.
Exercise 12 — argparse vs click: one advantage of each. Intermediate
argparse: stdlib; click: ergonomics, colors, testing with CliRunner.
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).