Introduction
Every developer has a folder of one-off scripts: rename files, convert CSVs, ping APIs. They work — but they’re not tools. A real CLI has --help, colored output, progress bars, and a clean install.
Typer (built on Click) + Rich (terminal styling) is the modern Python stack for this. In 20 minutes you’ll turn a script into a polished, installable CLI.
Setup
pip install typer rich
Step 1: Your first command
# cli.py
import typer
app = typer.Typer()
@app.command()
def hello(name: str, count: int = 1):
"""Say hello to NAME, COUNT times."""
for _ in range(count):
typer.echo(f"Hello {name}!")
if __name__ == "__main__":
app()
Run it:
python cli.py hello Galvan --count 3
# Hello Galvan!
# Hello Galvan!
# Hello Galvan!
Typer reads the type hints and builds --help automatically:
python cli.py hello --help
Step 2: Add Rich for beautiful output
import typer
from rich.console import Console
from rich.table import Table
console = Console()
app = typer.Typer()
@app.command()
def users(limit: int = 10):
"""List the top users."""
table = Table(title="Top Users")
table.add_column("Name", style="cyan")
table.add_column("Score", justify="right", style="green")
for i in range(limit):
table.add_row(f"User {i+1}", str(100 - i))
console.print(table)
Rich gives you tables, progress bars, syntax highlighting, and colored text — all in the terminal.
Step 3: Progress bars for long tasks
from rich.progress import track
import time
@app.command()
def process(files: list[str]):
"""Process a list of files."""
for f in track(files, description="Processing..."):
time.sleep(0.5) # your real work here
console.print(f"[green]✓[/] {f}")
Step 4: Confirmations and prompts
@app.command()
def delete(path: str):
"""Delete a file (with confirmation)."""
if not typer.confirm(f"Really delete {path}?"):
raise typer.Abort()
# ... delete
console.print(f"[red]Deleted[/] {path}")
Step 5: Subcommands (groups)
app = typer.Typer()
db_app = typer.Typer()
app.add_typer(db_app, name="db")
@db_app.command()
def migrate():
"""Run database migrations."""
console.print("[blue]Migrating...[/]")
@db_app.command()
def seed():
"""Seed the database."""
console.print("[blue]Seeding...[/]")
Usage: python cli.py db migrate. This is how tools like git and docker structure their CLIs.
Step 6: Make it installable
Create pyproject.toml:
[project]
name = "mytool"
version = "0.1.0"
dependencies = ["typer", "rich"]
[project.scripts]
mytool = "cli:app"
Then:
pip install -e .
mytool --help
Now mytool is a real command on your PATH. Ship it to PyPI with python -m build && twine upload dist/*.
Step 7: Environment variables & config
import os
@app.command()
def deploy(env: str = typer.Option("dev", envvar="APP_ENV")):
"""Deploy to ENV (or $APP_ENV)."""
console.print(f"Deploying to [bold]{env}[/]")
Typer reads APP_ENV automatically if env isn’t passed. Great for CI/CD.
Common mistakes
print()instead ofconsole.print()— loses colors and Rich formatting.- No
--helpdocstrings — Typer uses the function docstring as the command description. Write them. - Hardcoded paths — use
pathlib.Pathand accept them as arguments. - Forgetting
if __name__ == "__main__"— breakspip installentrypoints. - Mixing sync and async — Typer is sync by default; use
asyncio.run()inside commands for async work.
Key Concepts
- Typer = CLI framework from type hints
- Rich = terminal styling (tables, progress, colors)
- Subcommands = grouped commands (
tool db migrate) - Entry points =
pip install-able commands - Env vars =
envvar=for config
What to Try Next
- Turn your file organizer script into a CLI with a
--dry-runflag. - Add a
--jsonoutput flag for scripting (machine-readable output). - Build a Streamlit launcher CLI that scaffolds new apps.
- Publish to PyPI — your first open-source tool.
FAQ
Typer vs Click vs argparse?
argparse is built-in but verbose. Click is powerful but decorator-heavy. Typer = Click + type hints + less boilerplate. For new projects, Typer is the default choice; it’s literally “Click with type hints.”
Can Typer do async commands?
Not natively — wrap with asyncio.run() inside the command. For fully async CLIs, consider asyncio + a manual parser, but that’s rare.
How do I test a Typer CLI?
Use typer.testing.CliRunner:
from typer.testing import CliRunner
runner = CliRunner()
result = runner.invoke(app, ["hello", "Galvan"])
assert result.exit_code == 0