Skip to main content

Build Command-Line Tools with argparse and sys.argv

Intermediate25 min5 exercises75 XP
0/5 exercises

Most Python scripts you've written so far run the same way every time. But what if you want the user to choose what your script does? That's where command-line arguments come in. Instead of hardcoding values, you let users pass them when they run your script.

What Are Command-Line Arguments?

When you type python greet.py --name Alice in your terminal, --name and Alice are command-line arguments. Your script can read them and change its behavior. Think of them like function parameters, but for entire programs.


The Raw Approach: sys.argv

sys.argv is a list of strings that holds every argument passed to your script. The first element (sys.argv[0]) is the script name, and the rest are the arguments.

Python
Loading editor...

Parsing sys.argv manually works for simple scripts, but it quickly becomes messy. You need to handle missing arguments, wrong types, help messages, and optional flags all by yourself. That's why Python provides argparse.


argparse: The Professional Approach

The argparse module does the heavy lifting for you: it parses arguments, validates types, generates help messages, and handles errors gracefully. Here's the basic workflow:

Python
Loading editor...

Notice how we pass ['Alice'] to parse_args(). In a real terminal, you'd call parse_args() with no arguments and it would read from sys.argv automatically.


Positional vs Optional Arguments

Arguments come in two flavors. Positional arguments are required and identified by their position. Optional arguments start with - or -- and can appear in any order.

Python
Loading editor...

Type Checking and Choices

argparse can validate types and restrict values automatically. No more manual int() conversions or if value not in [...] checks.

Python
Loading editor...

Subparsers: Git-Style Subcommands

Tools like git use subcommands: git commit, git push, git log. Each subcommand has its own set of arguments. argparse handles this with add_subparsers().

Python
Loading editor...

Generating Help Automatically

One of argparse's best features is automatic help generation. Every argument's help text, type, default, and choices are combined into a formatted help message.

Python
Loading editor...

Practice Exercises

Parse sys.argv Manually
Write Code

Simulate a command-line greeting script:

1. Set sys.argv = ['greet.py', 'Alice', 'Bob', 'Charlie']

2. Extract the script name and the list of names (everything after index 0)

3. Print the script name on one line

4. Print a greeting for each name in the format Hello, <name>!

Loading editor...
Build a Basic argparse CLI
Write Code

Create an argparse-based greeting tool:

1. Create an ArgumentParser with description 'Greeting tool'

2. Add a positional argument name

3. Add an optional argument --greeting with default 'Hello'

4. Parse the args ['World', '--greeting', 'Hi']

5. Print the result in the format <greeting>, <name>!

Expected output: Hi, World!

Loading editor...
Type Validation and Choices
Write Code

Create a calculator CLI with argparse:

1. Add two positional arguments a and b, both with type=float

2. Add an optional argument --op with choices=['add', 'sub', 'mul'] and default='add'

3. Parse ['10', '3', '--op', 'mul']

4. Compute and print the result

Expected output: 30.0

Loading editor...
Fix the argparse Bug
Fix the Bug

The code below has bugs that prevent it from working correctly. Fix the issues so it prints:

Searching for: python
Max results: 5
Verbose: True
Loading editor...
Build a Subcommand CLI
Write Code

Create a note-taking CLI with two subcommands:

1. add subcommand with a positional text argument and optional --tag (default: 'general')

2. show subcommand with an optional --count argument of type=int (default: 5)

Parse ['add', 'Buy milk', '--tag', 'shopping'] and print:

Command: add
Text: Buy milk
Tag: shopping
Loading editor...