CLI Tools Competent¶
🌐 Web & APIs Track · Level 2
When you'd use this
Build command-line interfaces with argparse, click and typer.
Build command-line tools — scripts with flags, subcommands, and help text — using argparse, click, or typer instead of parsing sys.argv by hand.
argparse (built-in)¶
The standard-library parser — no dependencies. Use for scripts where you don't want to add a package.
import argparse
parser = argparse.ArgumentParser(description="Greet someone")
parser.add_argument("name", help="Name to greet")
parser.add_argument("-n", "--times", type=int, default=1, help="Times to greet")
args = parser.parse_args()
for _ in range(args.times):
print(f"Hello, {args.name}!")
click (third-party, declarative)¶
Build CLIs with decorators and automatic help — use for richer tools with subcommands and options.
import click
@click.command()
@click.argument("name")
@click.option("--times", "-n", default=1, help="Times to greet")
def greet(name, times):
"""Greet someone NAME times."""
for _ in range(times):
click.echo(f"Hello, {name}!")
if __name__ == "__main__":
greet()
typer (modern, type-hint based)¶
Define commands with plain type-hinted functions — the least-boilerplate option, built on click.
import typer
app = typer.Typer()
@app.command()
def greet(name: str, times: int = 1):
"""Greet someone."""
for _ in range(times):
typer.echo(f"Hello, {name}!")
if __name__ == "__main__":
app()
When to use what¶
Pick argparse for zero-dependency scripts, click/typer for larger multi-command tools.
| Tool | Best for |
|---|---|
argparse | Standard library, no deps, simple scripts |
click | Multi-command CLIs, complex options |
typer | Modern apps, type hints, auto-completion |
Practice exercises¶
- Build a file search CLI:
finder --ext .py --path ./src - Create a multi-command CLI with
add,remove,listsubcommands. - Add auto-completion and colored output with typer/rich.
💬 Discussion
Have a question about this topic? Found an error? Share your thoughts below.