Argparse — CLI Tools
Turn Python scripts into professional command-line tools with arguments, flags, type checking, defaults, and auto-generated --help pages.
"argparse turns a Python script into a proper command-line tool — complete with flags, type checking, default values, and a --help page — all without writing a single if/sys.argv line."
— ShuraiThe Problem: Manual Argument Parsing is Fragile
import sys
name = sys.argv[1] # crashes if
# user forgets it
# No --help
# No type checking
# No default values
# Error messages: cryptic
import argparse
parser = ArgumentParser()
parser.add_argument("name")
args = parser.parse_args()
# --help generated free
# Types converted auto
# Defaults handled
# Clear error messages
The Three Argument Types
Positional
filename
Required. Identified by its position. python script.py data.csv
Optional
--count
Optional. Starts with --. Has a default value. --count 5
Flag
--verbose
Boolean switch. True if present, False if absent. --verbose
Building Your First CLI Tool
import argparse
parser = argparse.ArgumentParser(
description="Greet one or more people"
)
# 1. Positional — required, no default
parser.add_argument("name",
help="Name of the person to greet")
# 2. Optional — has a default value
parser.add_argument("--times",
type=int, default=1,
help="How many times to print the greeting (default: 1)")
# 3. Flag — True if present on command line, False if not
parser.add_argument("--shout",
action="store_true",
help="Print in uppercase")
args = parser.parse_args() # parse + validate everything
msg = f"Hello, {args.name}!"
if args.shout:
msg = msg.upper()
for _ in range(args.times):
print(msg)
python greet.py Riya
# Hello, Riya!
python greet.py Riya --times 3 --shout
# HELLO, RIYA!
# HELLO, RIYA!
# HELLO, RIYA!
python greet.py --help
# usage: greet.py [-h] [--times TIMES] [--shout] name
#
# Greet one or more people
#
# positional arguments:
# name Name of the person to greet
#
# options:
# --times TIMES How many times to print the greeting (default: 1)
# --shout Print in uppercase
python greet.py # forgot the required argument
# error: the following arguments are required: name
Advanced Features — Choices, Short Flags, Mutually Exclusive
# Restrict value to a fixed set of choices
parser.add_argument("--format",
choices=["csv", "json", "xml"], default="csv",
help="Output format")
# --format pdf → error: argument --format: invalid choice: pdf
# Short flag alias: --verbose or -v both work
parser.add_argument("-v", "--verbose", action="store_true")
# Mutually exclusive: --compress and --no-compress can't both be set
group = parser.add_mutually_exclusive_group()
group.add_argument("--compress", action="store_true")
group.add_argument("--no-compress", action="store_true")
Real Example — CSV File Analyser
import argparse, csv, statistics
parser = argparse.ArgumentParser(description="Analyse a numeric CSV column")
parser.add_argument("file", help="Path to CSV file")
parser.add_argument("column", help="Column name to analyse")
parser.add_argument("--top", type=int, default=5, help="Show top N values")
parser.add_argument("--no-stats", action="store_true", help="Skip summary stats")
args = parser.parse_args()
with open(args.file) as f:
rows = list(csv.DictReader(f))
values = [float(r[args.column]) for r in rows]
if not args.no_stats: # argparse converts --no-stats → no_stats
print(f"Count : {len(values)}")
print(f"Mean : {statistics.mean(values):.2f}")
print(f"Stdev : {statistics.stdev(values):.2f}")
print(f"Min : {min(values):.2f} Max: {max(values):.2f}")
print(f"
Top {args.top} values:")
for v in sorted(values, reverse=True)[:args.top]:
print(f" {v:.2f}")
# python analyse.py sales.csv amount --top 3
# python analyse.py scores.csv grade --no-stats
"The --help flag is completely free with argparse — every help= string you write appears there automatically. Good help text is documentation that lives with the code and never goes out of date."
— Shurai🧠 Quiz — Q1
What is the main advantage of argparse over manually reading sys.argv?
🧠 Quiz — Q2
What is the difference between a positional argument and an optional argument in argparse?
🧠 Quiz — Q3
What does action="store_true" do when added to an argument?
🧠 Quiz — Q4
argparse converts --output-file to which attribute name on the args object?