argparse
Build command-line interfaces that accept arguments and options
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Why command-line arguments matter
So far, your programs have hard-coded their inputs. To process a different file, you edit the code and change the filename. To adjust a setting, you modify a variable. This works for learning but fails in practice.
Command-line arguments let users configure your program when they run it:
python organizer.py --directory ~/Downloads --verboseNo code changes needed. The user passes options from the terminal, and your program reads them.
The argparse module
argparse is Python's built-in module for parsing command-line arguments. It handles:
- Defining which arguments your program accepts
- Parsing the values the user provides
- Generating help text automatically
- Showing error messages for invalid input
Building a parser
Every CLI follows the same three steps:
import argparse
# 1. Create a parser
parser = argparse.ArgumentParser(description="My tool")
# 2. Add arguments
parser.add_argument("filename", help="File to process")
parser.add_argument("--verbose", action="store_true", help="Show details")
# 3. Parse the command line
args = parser.parse_args()
print(args.filename) # The positional argument
print(args.verbose) # True or FalsePositional vs optional arguments
Positional arguments have no prefix. They are required and identified by position:
parser.add_argument("filename") # RequiredOptional arguments start with --. They are identified by name and can have defaults:
parser.add_argument("--output", default="result.txt") # Optional, defaults to "result.txt"
parser.add_argument("--count", type=int, default=10) # Optional, must be intThe type parameter tells argparse to convert the string input to the specified type. Without it, all arguments are strings.
Automatic help
argparse generates a --help flag for free:
$ python tool.py --help
usage: tool.py [-h] [--output OUTPUT] filename
My tool
positional arguments:
filename File to process
options:
-h, --help show this help message and exit
--output OUTPUT Output file pathThis is why the help parameter matters in add_argument() — it becomes the description users see.
Your task
Build a greeter CLI that accepts a name and optional greeting style. You will use parse_args([...]) with a test list instead of reading from the actual command line — this lets you test the argument parsing in the code editor.
Instructions
Build a CLI argument parser for a greeting tool.
- Import the
argparsemodule. - Create a variable named
parserand assign itargparse.ArgumentParser(description="A friendly greeter"). - Call
parser.add_argument("name", help="Name to greet"). - Call
parser.add_argument("--greeting", default="Hello", help="Greeting to use"). - Call
parser.add_argument("--shout", action="store_true", help="Shout the greeting"). - Create a variable named
argsand assign itparser.parse_args(["Alice", "--greeting", "Hi", "--shout"]). - Create a variable named
messageand assign itf"{args.greeting}, {args.name}!". - Add an
ifstatement: ifargs.shoutis true, assignmessage.upper()tomessage. - Call
print()withmessage.
from pathlib import Path
import os
current = Path.cwd()
print(f"Current directory: {current}")
home = Path.home()
print(f"Home directory: {home}")
test_path = Path("example.txt")
print(f"Name: {test_path.name}")
print(f"Stem: {test_path.stem}")
print(f"Suffix: {test_path.suffix}")
from datetime import datetime, date, timedelta
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))
birthday = date(2000, 6, 15)
today = date.today()
age_days = (today - birthday).days
print(f"Days since birthday: {age_days}")
next_week = today + timedelta(days=7)
print(f"One week from today: {next_week.strftime('%B %d, %Y')}")
from collections import Counter, defaultdict, namedtuple
words = ["python", "java", "python", "rust", "java", "python", "go", "rust"]
word_counts = Counter(words)
print(word_counts.most_common(3))
scores = defaultdict(list)
scores["math"].append(95)
scores["math"].append(87)
scores["science"].append(92)
print(dict(scores))
Student = namedtuple("Student", ["name", "grade", "gpa"])
s = Student("Alice", 10, 3.8)
print(f"{s.name}: Grade {s.grade}, GPA {s.gpa}")
# Step 1: Import argparse
# Step 2: Create the argument parser
# Step 3: Add positional argument "name"
# Step 4: Add optional argument "--greeting" with default "Hello"
# Step 5: Add optional argument "--shout" as a boolean flag
# Step 6: Parse test arguments
# Step 7: Build the message
# Step 8: If shout is true, uppercase the message
# Step 9: Print the message
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding