Skip to main content
Editor

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
import sys
# In a real terminal, running: python script.py hello world
# would give: sys.argv = ['script.py', 'hello', 'world']
# Let's simulate it:
sys.argv = ['greet.py', 'Alice', 'Bob']
script_name = sys.argv[0]
names = sys.argv[1:]
print(f'Script: {script_name}')
for name in names:
print(f'Hello, {name}!')
Output
Script: greet.py
Hello, Alice!
Hello, Bob!

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
import argparse
# 1. Create a parser
parser = argparse.ArgumentParser(
description='A friendly greeting program'
)
# 2. Add arguments
parser.add_argument('name', help='Name of the person to greet')
# 3. Parse (using explicit list instead of sys.argv)
args = parser.parse_args(['Alice'])
# 4. Use the parsed values
print(f'Hello, {args.name}!')
Output
Hello, Alice!

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
import argparse
parser = argparse.ArgumentParser(description='File converter')
# Positional (required)
parser.add_argument('filename', help='File to convert')
# Optional with short and long form
parser.add_argument('-f', '--format', default='csv',
help='Output format (default: csv)')
parser.add_argument('-v', '--verbose', action='store_true',
help='Enable verbose output')
# Simulate: python convert.py data.json --format csv --verbose
args = parser.parse_args(['data.json', '--format', 'csv', '--verbose'])
print(f'File: {args.filename}')
print(f'Format: {args.format}')
print(f'Verbose: {args.verbose}')
Output
File: data.json
Format: csv
Verbose: True

Type Checking and Choices

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

Python
import argparse
parser = argparse.ArgumentParser(description='Image resizer')
# type= converts the string argument to the specified type
parser.add_argument('--width', type=int, default=800,
help='Width in pixels')
parser.add_argument('--height', type=int, default=600,
help='Height in pixels')
# choices= restricts to specific values
parser.add_argument('--quality', choices=['low', 'medium', 'high'],
default='medium', help='Output quality')
# nargs= accepts multiple values
parser.add_argument('--sizes', type=int, nargs='+',
help='Multiple sizes to generate')
args = parser.parse_args(['--width', '1024', '--quality', 'high',
'--sizes', '100', '200', '300'])
print(f'Width: {args.width} (type: {type(args.width).__name__})')
print(f'Height: {args.height}')
print(f'Quality: {args.quality}')
print(f'Sizes: {args.sizes}')
Output
Width: 1024 (type: int)
Height: 600
Quality: high
Sizes: [100, 200, 300]

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
import argparse
parser = argparse.ArgumentParser(description='Task manager')
subparsers = parser.add_subparsers(dest='command', help='Available commands')
# "add" subcommand
add_parser = subparsers.add_parser('add', help='Add a new task')
add_parser.add_argument('title', help='Task title')
add_parser.add_argument('--priority', choices=['low', 'medium', 'high'],
default='medium')
# "list" subcommand
list_parser = subparsers.add_parser('list', help='List all tasks')
list_parser.add_argument('--done', action='store_true',
help='Show only completed tasks')
# Simulate: python tasks.py add "Buy groceries" --priority high
args = parser.parse_args(['add', 'Buy groceries', '--priority', 'high'])
if args.command == 'add':
print(f'Adding task: {args.title} (priority: {args.priority})')
elif args.command == 'list':
print(f'Listing tasks (done only: {args.done})')
Output
Adding task: Buy groceries (priority: high)

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
import argparse
parser = argparse.ArgumentParser(
description='A simple calculator CLI',
epilog='Example: python calc.py 10 20 --operation mul'
)
parser.add_argument('x', type=float, help='First number')
parser.add_argument('y', type=float, help='Second number')
parser.add_argument('--operation', '-o',
choices=['add', 'sub', 'mul', 'div'],
default='add',
help='Operation to perform (default: add)')
# Print the auto-generated help
parser.print_help()
print('\n--- Running with args ---')
args = parser.parse_args(['10', '20', '--operation', 'mul'])
ops = {
'add': lambda a, b: a + b,
'sub': lambda a, b: a - b,
'mul': lambda a, b: a * b,
'div': lambda a, b: a / b if b != 0 else 'Error: division by zero',
}
result = ops[args.operation](args.x, args.y)
print(f'{args.x} {args.operation} {args.y} = {result}')
Output
usage: greet.py [-h] [--operation {add,sub,mul,div}] x y

A simple calculator CLI

positional arguments:
  x                     First number
  y                     Second number

options:
  -h, --help            show this help message and exit
  --operation, -o {add,sub,mul,div}
                        Operation to perform (default: add)

Example: python calc.py 10 20 --operation mul

--- Running with args ---
10.0 mul 20.0 = 200.0

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

import sys
# Set sys.argv and process the arguments
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!

import argparse
# Build the parser and parse arguments
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

import argparse
# Build a calculator CLI
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
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('query')
parser.add_argument('--max', type=str, default=5)
parser.add_argument('--verbose', action='store_false')
args = parser.parse_args(['python', '--max', '5', '--verbose'])
print(f'Searching for: {args.query}')
print(f'Max results: {args.max}')
print(f'Verbose: {args.verbose}')
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
import argparse
# Build a subcommand CLI for notes

Harder problems

More problems on this topic: Parsing

Related Tutorials

Was this tutorial helpful?