Part 02 / Topic 2 of 6
Command-line tools
Integration work ships as small command-line tools far more often than as apps: a sync job, a backfill, a checker. argparse gives you flags, help text, and correct exit codes for free:
# examples/01_a_command_line_tool_with_argparse.py
import argparse
def build_parser():
p = argparse.ArgumentParser(prog="acme-sync", description="Sync shipments from Acme's API.")
p.add_argument("--since", required=True, help="Only fetch shipments updated after this date (YYYY-MM-DD)")
p.add_argument("--dry-run", action="store_true", help="Show what would change without writing")
p.add_argument("--page-size", type=int, default=100)
return p
args = build_parser().parse_args(["--since", "2025-04-01", "--dry-run"])
print(args)
try:
build_parser().parse_args(["--since", "2025-04-01", "--page-size", "abc"])
except SystemExit as e:
print("bad arguments exit code:", e.code)
# Namespace(since='2025-04-01', dry_run=True, page_size=100)
# bad arguments exit code: 2
Three flags earn their place on almost every customer tool:
--dry-run— show what would change without writing anything. The first run of your tool against a customer's system should always be a dry run; it builds trust before the first real write.--since/ scoping flags — never force an all-or-nothing run.- Exit codes —
0success, non-zero failure (argparse itself exits2on bad arguments). Schedulers and shell scripts read exit codes, not prose.
🧪 Quick quiz — answer from memory, then check.
- What exit code does argparse use when arguments are invalid?
Show the answer
2. Passing --page-size abc made argparse exit with code 2 in the example. (verified against the example output above)
- Why give a sync script a
--dry-runflag?
Show the answer
So the customer can see what would change before anything is written. Dry runs build trust before the first real write into a customer's system.
Done here? The practice set for Part 2 — 4 exercises with solutions — is on the part page.