Command-line tools are programs you run in the terminal. They take arguments and flags (like git commit -m 'message') and are incredibly powerful for automation. Python's argparse module makes them easy to build.
Key Concepts
sys.argv sys.argv is a list of command-line arguments. sys.argv[0] is the script name. sys.argv[1] is the first argument. Simple but fragile for complex tools.
argparse Module import argparse parser = argparse.ArgumentParser(description='My tool') parser.add_argument('name') parser.add_argument('--count', type=int, default=1) args = parser.parse_args() Argparse generates --help automatically.
Positional vs Optional Args Positional: required, no prefix. mytool filename.txt Optional: starts with --, optional. mytool --verbose Flags: boolean --debug True/False. parser.add_argument('--debug', action='store_true')
Subcommands Like git: git add, git commit, git push — these are subcommands. subparsers = parser.add_subparsers(dest='command') add_parser = subparsers.add_parser('add')
# Simulated argparse CLI tool (runs without command line)
import argparse
import sys
def run_cli(args_list):
parser = argparse.ArgumentParser(
prog="gradebook",
description="A student gradebook CLI tool"
)
subparsers = parser.add_subparsers(dest="command")
# add command
add_p = subparsers.add_parser("add", help="Add a student score")
add_p.add_argument("name")
add_p.add_argument("score", type=int)
# average command
avg_p = subparsers.add_parser("average", help="Show class average")
avg_p.add_argument("--threshold", type=int, default=0,
help="Only include scores above threshold")
args = parser.parse_args(args_list)
return args
students = {"Alex": 92, "Brooke": 85, "Carlos": 78, "Dana": 95}
commands = [
["add", "Eli", "88"],
["add", "Fiona", "76"],
["average"],
["average", "--threshold", "80"],
]
for cmd in commands:
args = run_cli(cmd)
print(f"$ gradebook {" ".join(cmd)}")
if args.command == "add":
students[args.name] = args.score
print(f" Added: {args.name} = {args.score}")
elif args.command == "average":
filtered = {k:v for k,v in students.items() if v > args.threshold}
if filtered:
avg = sum(filtered.values())/len(filtered)
print(f" Average (>{args.threshold}): {avg:.1f} ({len(filtered)} students)")
print()
✅ Check Your Understanding
1. What does argparse generate automatically?
A GUI window
--help documentation
Database connections
API keys
2. A positional argument in argparse is:
Optional with a -- prefix
Required and has no prefix
A boolean flag
A subcommand
3. What is a subcommand? (e.g., git commit)
A nested function
A completely different program
A specific command mode within a tool
A type of argument