argparse is Python’s built-in module for command-line tools. You describe the arguments your script accepts, like a folder, a --limit number, or a --verbose switch, and argparse reads them, converts their types, rejects bad input with a clear message, and generates a --help page automatically.
Most scripts start with values hard-coded at the top: the folder to scan, the number of results, the output file. Every change means editing the code. A command-line interface (CLI) turns that script into a tool: run it with different options, use it in other scripts and scheduled tasks, and share it with teammates who never need to open the code.
This guide builds two real tools: a “find the largest files” utility and a small to-do list with subcommands. All commands and output shown were run with Python 3.12 (newer versions add color to the help output, but the content is the same). It builds on Automate Everyday Tasks With Python.
Arguments 101
Command-line tools take two kinds of arguments:
- Positional arguments are required and identified by their position: in
python bigfiles.py ~/Downloads, the folder. - Optional arguments start with
-or--and can appear in any order:--limit 10,-v. They usually have defaults.
Python puts everything you typed in sys.argv, a list of strings. You could parse that list yourself, but argparse handles the details: types, defaults, missing values, typos, and help text.
A Complete Tool: Find Large Files
Save this as bigfiles.py:
"""Find the largest files in a folder."""
import argparse
import json
import sys
from pathlib import Path
def parse_args():
parser = argparse.ArgumentParser(
description="Find the largest files in a folder.",
epilog="Example: python bigfiles.py ~/Downloads --min-size 50 --limit 10",
)
parser.add_argument("folder", type=Path, help="folder to search")
parser.add_argument("--min-size", type=float, default=10,
help="smallest file to report, in MB (default: %(default)s)")
parser.add_argument("-n", "--limit", type=int, default=5,
help="how many files to show (default: %(default)s)")
parser.add_argument("-e", "--ext", action="append",
help="only include this extension, like .log (repeatable)")
parser.add_argument("--format", choices=["table", "json"], default="table",
help="output format (default: %(default)s)")
parser.add_argument("-v", "--verbose", action="store_true",
help="print extra details")
return parser.parse_args()
def main():
args = parse_args()
if not args.folder.is_dir():
print(f"Error: {args.folder} is not a folder", file=sys.stderr)
return 1
extensions = {e.lower() for e in args.ext} if args.ext else None
min_bytes = args.min_size * 1024 * 1024
files = []
for path in args.folder.rglob("*"):
if not path.is_file():
continue
if extensions and path.suffix.lower() not in extensions:
continue
size = path.stat().st_size
if size >= min_bytes:
files.append((size, path))
files.sort(reverse=True)
top = files[: args.limit]
if args.verbose:
print(f"Searched {args.folder}, {len(files)} files over {args.min_size} MB", file=sys.stderr)
if args.format == "json":
data = [{"path": str(p), "size_mb": round(s / 1024 / 1024, 1)} for s, p in top]
print(json.dumps(data, indent=2))
else:
for size, path in top:
print(f"{size / 1024 / 1024:>8.1f} MB {path}")
return 0
if __name__ == "__main__":
sys.exit(main())
The pattern is always the same: create an ArgumentParser, add arguments, call parse_args(), and use the results as attributes, like args.folder and args.limit. Dashes in option names become underscores, so --min-size is args.min_size.
The Free Help Page
Run it with --help (or -h), and argparse writes the documentation for you from your help= texts:
python bigfiles.py --help
usage: bigfiles.py [-h] [--min-size MIN_SIZE] [-n LIMIT] [-e EXT]
[--format {table,json}] [-v]
folder
Find the largest files in a folder.
positional arguments:
folder folder to search
options:
-h, --help show this help message and exit
--min-size MIN_SIZE smallest file to report, in MB (default: 10)
-n LIMIT, --limit LIMIT
how many files to show (default: 5)
-e EXT, --ext EXT only include this extension, like .log (repeatable)
--format {table,json}
output format (default: table)
-v, --verbose print extra details
Example: python bigfiles.py ~/Downloads --min-size 50 --limit 10
%(default)s inserts each default value, so the help can’t get out of date.
Using the Tool
With only the required folder:
python bigfiles.py demo
48.0 MB demo/videos/intro.mp4
25.0 MB demo/backup.zip
12.0 MB demo/logs/app.log
Change the defaults with options, in any order. Short forms like -n work too:
python bigfiles.py demo --min-size 5 -n 2
48.0 MB demo/videos/intro.mp4
25.0 MB demo/backup.zip
action="append" lets an option repeat, collecting the values in a list:
python bigfiles.py demo --ext .log --ext .zip --min-size 1
25.0 MB demo/backup.zip
12.0 MB demo/logs/app.log
3.0 MB demo/logs/old.log
And --format json produces output other programs can read, while -v adds details:
python bigfiles.py demo --format json -n 2 -v
Searched demo, 3 files over 10 MB
[
{
"path": "demo/videos/intro.mp4",
"size_mb": 48.0
},
{
"path": "demo/backup.zip",
"size_mb": 25.0
}
]
The Argument Options You’ll Use Most
| Option | What it does | Example in the tool |
|---|---|---|
type= | Converts the text to a type (and rejects bad values) | type=int, type=float, type=Path |
default= | The value when the option isn’t given | default=5 |
choices= | Allows only listed values | choices=["table", "json"] |
action="store_true" | A switch: True if present, False if not | --verbose |
action="append" | Lets an option repeat, collecting a list | --ext |
required=True | Makes an option mandatory | |
nargs="+" | Accepts one or more values | files that takes several paths |
help= | The description shown by --help |
Errors for Free
Because the arguments are typed and validated, bad input never reaches your code. argparse prints the usage line and a clear message:
python bigfiles.py demo --limit ten
usage: bigfiles.py [-h] [--min-size MIN_SIZE] [-n LIMIT] [-e EXT]
[--format {table,json}] [-v]
folder
bigfiles.py: error: argument -n/--limit: invalid int value: 'ten'
python bigfiles.py
usage: bigfiles.py [-h] [--min-size MIN_SIZE] [-n LIMIT] [-e EXT]
[--format {table,json}] [-v]
folder
bigfiles.py: error: the following arguments are required: folder
python bigfiles.py demo --format csv
usage: bigfiles.py [-h] [--min-size MIN_SIZE] [-n LIMIT] [-e EXT]
[--format {table,json}] [-v]
folder
bigfiles.py: error: argument --format: invalid choice: 'csv' (choose from table, json)
For checks argparse can’t do, like “is this folder real?”, the tool prints its own error and returns a non-zero code:
python bigfiles.py nowhere
Error: nowhere is not a folder
Exit Codes and Output Streams
Well-behaved tools follow two conventions that make them easy to use from scripts and schedulers:
- Exit codes:
0means success; anything else means failure. argparse exits with2for usage errors, and the tool returns1when the folder is missing, throughsys.exit(main()). A shell script or Task Scheduler can check this code; in PowerShell it’s in$LASTEXITCODE, as covered in PowerShell vs. Command Prompt. - stdout vs. stderr: results go to standard output with
print(), while errors and extra details go to standard error withprint(..., file=sys.stderr). That’s why--format json -vstill produces clean JSON when you save it:python bigfiles.py demo --format json -v > big.jsonwrites only the JSON to the file, and the “Searched…” line stays on screen.
Subcommands: One Tool, Several Actions
Tools like git have subcommands: git add, git commit, git log, each with its own options. argparse supports this with add_subparsers(). Here’s a tiny to-do list, tasks.py:
"""A tiny to-do list with subcommands: add, list, and done."""
import argparse
import json
from pathlib import Path
TASKS_FILE = Path("tasks.json")
def load():
return json.loads(TASKS_FILE.read_text()) if TASKS_FILE.exists() else []
def save(tasks):
TASKS_FILE.write_text(json.dumps(tasks, indent=2))
def cmd_add(args):
tasks = load()
tasks.append({"title": args.title, "client": args.client, "done": False})
save(tasks)
print(f"Added task {len(tasks)}: {args.title}")
def cmd_list(args):
for number, task in enumerate(load(), start=1):
if args.pending and task["done"]:
continue
mark = "x" if task["done"] else " "
client = f" ({task['client']})" if task["client"] else ""
print(f"[{mark}] {number}. {task['title']}{client}")
def cmd_done(args):
tasks = load()
tasks[args.number - 1]["done"] = True
save(tasks)
print(f"Completed: {tasks[args.number - 1]['title']}")
def main():
parser = argparse.ArgumentParser(description="Track client tasks.")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add", help="add a task")
add.add_argument("title")
add.add_argument("--client", default="")
add.set_defaults(func=cmd_add)
show = sub.add_parser("list", help="list tasks")
show.add_argument("--pending", action="store_true", help="hide finished tasks")
show.set_defaults(func=cmd_list)
done = sub.add_parser("done", help="mark a task as finished")
done.add_argument("number", type=int)
done.set_defaults(func=cmd_done)
args = parser.parse_args()
args.func(args)
if __name__ == "__main__":
main()
Each subcommand gets its own parser and arguments, and set_defaults(func=...) connects it to the function that does the work:
python tasks.py add "Update menu page" --client "Bakery Lopez"
python tasks.py add "Renew SSL certificate"
python tasks.py done 2
python tasks.py list
Added task 1: Update menu page
Added task 2: Renew SSL certificate
Completed: Renew SSL certificate
[ ] 1. Update menu page (Bakery Lopez)
[x] 2. Renew SSL certificate
python tasks.py list --pending
[ ] 1. Update menu page (Bakery Lopez)
Quotes keep a title with spaces together as one argument. python tasks.py --help lists the subcommands, and python tasks.py add --help shows the options for add.
Making Your Tool Easy to Run
- Keep the
if __name__ == "__main__":guard, as explained in Python Basics: Modules and the Standard Library, so the file can also be imported and tested. - On macOS and Linux, add
#!/usr/bin/env python3as the first line and runchmod +x bigfiles.py. Then you can run./bigfiles.py demo. - Install it as a command. In a project with a
pyproject.toml, a[project.scripts]entry likebigfiles = "bigfiles:main"creates abigfilescommand when the project is installed, for example withuv tool install .(see Python uv). - Schedule it. A CLI is easy to run from cron or Task Scheduler with different options for different jobs.
argparse Alternatives
argparse is built in and covers most needs. Two popular third-party libraries build on the same ideas: Click uses decorators, and Typer builds the interface from type hints, similar to how FastAPI builds APIs. They’re worth a look for big tools; for scripts and team utilities, argparse has the advantage of needing nothing installed.
Common Mistakes to Avoid
- Forgetting
type=. Without it, every value is a string, so--limit 10gives you"10". - Using
type=bool.bool("False")isTrue. Useaction="store_true"for switches. - Printing errors to stdout. Send them to
sys.stderrso they don’t mix with results. - Always returning exit code 0. Return non-zero on failure so scripts and schedulers notice.
- Skipping
help=texts. The help page is your tool’s documentation; a few words per argument go a long way.
Frequently Asked Questions
What’s the difference between argparse and sys.argv?
sys.argv is the raw list of strings from the command line. argparse reads that list for you, converts types, applies defaults, validates input, and creates help and error messages.
How do I make an argument optional?
Give it a name starting with -- (an optional argument), with a default=. Positional arguments are required unless you set nargs="?".
Can argparse read values from environment variables?
Not directly, but you can use one as the default: default=os.environ.get("REPORT_DIR", ".").
Should I use argparse, Click, or Typer?
Start with argparse: it’s built in and good for most tools. Choose Click or Typer for large tools with many commands, if you don’t mind installing a dependency.
Conclusion
argparse turns a script with hard-coded values into a real command-line tool: describe positional and optional arguments with types, defaults, choices, and help text, and you get validation, error messages, and a --help page for free. Add subcommands for tools that do several things, send errors to stderr, return meaningful exit codes, and your scripts become tools you, your team, and your scheduled tasks can reuse every day.
