Arguments with argparse
beginner12 min readLesson 52 of 169
Speak-first CLIs: actions, optional extras, and free professional error handling.
Menus hard-code the conversation. Arguments let users speak first:
python todo.py add "buy milk"
python todo.py list
The stdlib module for this is argparse — here is the beginner slice:
import argparse
parser = argparse.ArgumentParser(description="Todo CLI")
parser.add_argument("action", choices=["add", "list", "done"])
parser.add_argument("text", nargs="?") # optional extra word(s)
args = parser.parse_args()
print(args.action, args.text)
parse_args() reads sys.argv for you, validates choices, and even prints
usage help with -h. Wrong usage exits with a clear error instead of crashing
with a traceback — professional behavior for free.