Part 16 / Topic 1 of 6
argparse, properly
You have already used argparse without being taught it (Stage 1's expense tracker, Stage 2's library manager both use it). This topic is where you learn what it is actually doing.
argparse (argument parser) turns the list of text a user typed after your program's name (sys.argv) into a typed, checked Python object. Think of it as the bouncer at a club door: it checks everyone's "ticket" (the arguments) against the rules before letting them in; your own code only ever sees people who already passed the check.
Real-world example: a tiny expense tool, one command at a time.
import argparse
parser = argparse.ArgumentParser(prog="expense")
parser.add_argument("amount", type=float) # positional, required
parser.add_argument("--category", "-c", default="other") # optional, with a default
args = parser.parse_args(["250", "--category", "food"])
print(args.amount, type(args.amount).__name__) # 250.0 float
print(args.category) # food
- A positional argument (
amount) has no--name; its position decides its meaning. - An optional argument starts with
--(and often a short-calias too). type=floatruns the text throughfloat(...)before your code seesargs.amount. Give it text that cannot convert andargparserejects it itself.parser.parse_args()with no argument reads the realsys.argv[1:]; passing a list (as above) is how you test it, or feed it a fixed command in a demo.
Subcommands, like git commit or git push
A real tool usually has several actions, not one. add_subparsers() gives each action its own mini-parser, with its own arguments.
import argparse
parser = argparse.ArgumentParser(prog="expense")
subparsers = parser.add_subparsers(dest="command", required=True)
add_parser = subparsers.add_parser("add")
add_parser.add_argument("amount", type=float)
add_parser.add_argument("--category", choices=["food", "travel", "rent", "other"], default="other")
subparsers.add_parser("total") # no extra arguments of its own
args = parser.parse_args(["add", "250", "--category", "food"])
print(args.command, args.amount, args.category) # add 250.0 food
dest="command"is the name the chosen subcommand is stored under (args.command).required=Truemeans some subcommand must be given, orargparseexits with an error (see below) instead of your code running with nothing to do.choices=[...]is a closed list: anything else is rejected immediately, with the same kind of error as a badtype=.
What happens on bad input
argparse never raises a normal Python exception for bad input. It prints a usage message to standard error and calls sys.exit(2) (exit code 2 is the Unix convention for "wrong command-line usage"). Catch SystemExit to see this without your program actually quitting:
try:
parser.parse_args(["add", "not-a-number"])
except SystemExit as error:
print("exit code:", error.code) # exit code: 2
This is also why Stage 1 and Stage 2's projects write # 2 = wrong command-line usage (printed by argparse) as a comment near their own parse_args() call.
--help, for free
Every parser gets a working -h/--help without you writing one line for it, built from the names, help= strings and choices= you already gave it. Here it is for real, from examples/01_argparse_expense_cli.py (which adds a help= string to each subcommand):
$ python 01_argparse_expense_cli.py --help
usage: expense [-h] {add,total} ...
A tiny expense tracker (one run = one in-memory list).
positional arguments:
{add,total}
add record one expense
total print the running total
options:
-h, --help show this help message and exit
Full, runnable programs: examples/01_argparse_expense_cli.py (subcommands, types, choices) and examples/02_argparse_unit_converter.py (defaults in more depth). Both print a guided demo when run with no arguments, and work normally with real arguments too.
Read more: the official argparse documentation.
Exercise 1: A chai stall order CLI
Scenario: A chai stall wants a command-line tool to log orders and print its menu, instead of shouting across the counter.
What to do: Inside main():
- Write
build_parser()with two subcommands:order(positionalitem, restricted to the menu's keys withchoices=;--qtyastype=intwith default1;--sizewithchoices=["small", "regular", "large"]and default"regular") andmenu(no arguments). - Run these three command lines through the parser, in order, printing
$ chai-stall <the command>before each result:order masala-chaiorder filter-coffee --qty 2 --size largemenu(print every item and price, sorted by name)
- Then try
order masala-chai --size giantinside atry/except SystemExit, and print the exit code.
Starting data:
MENU = {"masala-chai": 15, "filter-coffee": 20, "lemon-tea": 10}
Sample output:
$ chai-stall order masala-chai
1 x regular masala-chai = ₹15
$ chai-stall order filter-coffee --qty 2 --size large
2 x large filter-coffee = ₹40
$ chai-stall menu
filter-coffee: ₹20
lemon-tea: ₹10
masala-chai: ₹15
--- invalid size ---
usage: chai-stall order [-h] [--qty QTY] [--size {small,regular,large}]
{filter-coffee,lemon-tea,masala-chai}
chai-stall order: error: argument --size: invalid choice: 'giant' (choose from 'small', 'regular', 'large')
SystemExit code: 2
💡 Hint: choices=sorted(MENU) on the item argument reuses the menu's keys, so a typo is rejected before your code ever runs. The usage line's exact wrapping can differ by one space between terminals; the important parts are the error message and SystemExit code: 2.
Show the solution to Exercise 1
"""Exercise 1: A chai stall order CLI with argparse.
Run: python ex01.py (macOS/Linux: python3 ex01.py)
"""
import argparse
SIZES = ["small", "regular", "large"]
MENU = {"masala-chai": 15, "filter-coffee": 20, "lemon-tea": 10}
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="chai-stall")
subparsers = parser.add_subparsers(dest="command", required=True)
order = subparsers.add_parser("order")
order.add_argument("item", choices=sorted(MENU))
order.add_argument("--qty", type=int, default=1)
order.add_argument("--size", choices=SIZES, default="regular")
subparsers.add_parser("menu")
return parser
def run_order(args: argparse.Namespace) -> str:
price = MENU[args.item] * args.qty
return f"{args.qty} x {args.size} {args.item} = ₹{price}"
def run_menu() -> str:
lines = [f"{item}: ₹{price}" for item, price in sorted(MENU.items())]
return "\n".join(lines)
def main() -> None:
parser = build_parser()
sessions = [
["order", "masala-chai"],
["order", "filter-coffee", "--qty", "2", "--size", "large"],
["menu"],
]
for argv in sessions:
args = parser.parse_args(argv)
print(f"$ chai-stall {' '.join(argv)}")
if args.command == "order":
print(run_order(args))
else:
print(run_menu())
print("--- invalid size ---")
try:
parser.parse_args(["order", "masala-chai", "--size", "giant"])
except SystemExit as error:
print("SystemExit code:", error.code)
if __name__ == "__main__":
main()