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 --verbose

No 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 False

Positional vs optional arguments

Positional arguments have no prefix. They are required and identified by position:

parser.add_argument("filename")       # Required

Optional 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 int

The 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 path

This 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.

  1. Import the argparse module.
  2. Create a variable named parser and assign it argparse.ArgumentParser(description="A friendly greeter").
  3. Call parser.add_argument("name", help="Name to greet").
  4. Call parser.add_argument("--greeting", default="Hello", help="Greeting to use").
  5. Call parser.add_argument("--shout", action="store_true", help="Shout the greeting").
  6. Create a variable named args and assign it parser.parse_args(["Alice", "--greeting", "Hi", "--shout"]).
  7. Create a variable named message and assign it f"{args.greeting}, {args.name}!".
  8. Add an if statement: if args.shout is true, assign message.upper() to message.
  9. Call print() with message.