Lesson 41 of 59Libraries every Python developer knows
Command-Line Tools with Typer and Rich
Build real CLIs with Typer, make their output readable with Rich, and install them as commands with uv.
Every backend team ends up with scripts: seed the database, create an admin user, re-send failed webhooks, export last month's invoices. They usually start as a file full of sys.argv[1] and grow into something nobody wants to touch. Typer turns plain Python functions into proper command-line tools with options, validation and help text, all read from your type hints. Rich makes their output easy to read, with colours, tables, progress bars and tracebacks that point at the problem. Together they make an internal tool feel like a real product, and they take minutes to set up.
Your first Typer command
Install Typer with uv add typer. The smallest program is one function:
import typer
def main(name: str, count: int = 1, shout: bool = False) -> None:
"""Greet someone from the command line."""
for _ in range(count):
greeting = f"Hello, {name}!"
typer.echo(greeting.upper() if shout else greeting)
if __name__ == "__main__":
typer.run(main)uv run hello.py Adauv run hello.py Ada --count 3 --shoutuv run hello.py --helpuv run hello.py Ada --count lots # error: 'lots' is not a valid integerTyper reads the signature and builds the interface from it:
- A parameter without a default (
name) becomes a required positional argument. - A parameter with a default (
count,shout) becomes an option:--count 3. - The type hint decides parsing and validation.
intrejectslotswith a clear message, andboolbecomes a flag pair,--shout/--no-shout. - The docstring becomes the description in
--help. Underscores in names become dashes, sodry_runis--dry-run.
That is the whole trick, and it is the same idea FastAPI uses for query parameters. Both come from the same author and share the same philosophy: declare types once and get parsing, validation and docs for free.
Which option name does Typer create for this parameter?
def main(dry_run: bool = False): ...
Several commands in one tool
Real tools have subcommands, like git commit and git push. Create a typer.Typer() app and register functions with @app.command(). Use Annotated with typer.Argument and typer.Option to add help text and constraints, just like Query in FastAPI.
from pathlib import Path
from typing import Annotated
import typer
app = typer.Typer(help="Manage the todo database.", no_args_is_help=True)
@app.command()
def add(
title: Annotated[str, typer.Argument(help="What needs doing.")],
priority: Annotated[int, typer.Option("--priority", "-p", min=1, max=5, help="1 is most urgent.")] = 3,
) -> None:
"""Add a todo."""
todo = repo.add(title, priority)
typer.echo(f"Added #{todo.id}: {todo.title}")
@app.command()
def export(
out: Annotated[Path, typer.Option(help="CSV file to write.")] = Path("todos.csv"),
force: Annotated[bool, typer.Option(help="Overwrite an existing file.")] = False,
) -> None:
"""Export all todos to CSV."""
if out.exists() and not force:
typer.echo(f"{out} exists; pass --force to overwrite", err=True)
raise typer.Exit(code=1)
count = repo.export_csv(out)
typer.echo(f"Wrote {count} rows to {out}")
@app.command()
def purge() -> None:
"""Delete every completed todo."""
typer.confirm("Delete all completed todos?", abort=True)
typer.echo(f"Deleted {repo.purge_done()} todos")todo add "Write tests" -p 1todo export --out done.csv --forcetodo purgetodo --helpA few habits from this example worth copying:
- Exit codes matter.
raise typer.Exit(code=1)tells the shell, a CI job or a cron wrapper that the command failed. Exit code 0 means success. - Errors go to stderr (
err=True), so they do not end up inside a file when someone redirects the output. - Destructive commands confirm, and have a
--yesor--forceoption so they can still run in scripts. - Keep the command thin. The function parses input and calls into real code (
repo.add). That code is shared with your API and tested on its own.
todo export --out report.csv. The file already exists, and the command prints a message and returns normally. What does the job runner see?Growing the tool: groups, global options and settings
As a tool grows, group related commands into sub-apps, the way git remote add lives under git remote:
users_app = typer.Typer(help="Manage users.")
app.add_typer(users_app, name="users")
@users_app.command("create")
def create_user(email: str, admin: bool = False) -> None:
"""Create a user."""
...That gives you todo users create ada@example.com --admin. Options that apply to every command, such as --verbose or which database to use, belong in a callback, which runs before any subcommand:
@app.callback()
def main(
verbose: Annotated[bool, typer.Option("--verbose", "-v")] = False,
db_url: Annotated[str, typer.Option(envvar="TODO_DB_URL")] = "sqlite:///todo.db",
) -> None:
"""Manage the todo database."""
configure_logging(verbose)
connect(db_url)envvar= lets an option fall back to an environment variable, which is how the same command runs against your laptop's database locally and the real one inside a container. If your service already has a pydantic-settings Settings class, load it here instead of re-declaring every setting as an option. The CLI and the API should read configuration the same way.
--verbose to work for every command in your tool without repeating it in each function. Where does it go?Rich: output people can read
Rich formats terminal output. Typer already uses it for nicely formatted help and errors when it is installed, and you can use it directly for your own output. The main object is a Console.
from rich.console import Console
from rich.table import Table
console = Console()
err_console = Console(stderr=True)
@app.command("list")
def list_todos(show_done: bool = False) -> None:
"""Show todos as a table."""
table = Table(title="Todos")
table.add_column("ID", justify="right", style="dim")
table.add_column("Title")
table.add_column("Priority", justify="center")
table.add_column("Done", justify="center")
for todo in repo.list(include_done=show_done):
table.add_row(str(todo.id), todo.title, str(todo.priority), "yes" if todo.done else "")
console.print(table)
console.print(f"[bold green]{len(table.rows)}[/] todos shown")console.print understands markup in square brackets: [bold], [red], [dim], closed with [/]. Rich also notices when output is not a terminal, for example when piped to a file, and drops the colour codes so the file stays clean.
Three more Rich features you will use constantly:
from rich.progress import track
from rich.traceback import install
install(show_locals=True) # pretty tracebacks with local variables, once at startup
for user in track(users, description="Re-sending emails..."):
send_welcome(user) # a live progress bar with a time estimate
with console.status("Running migrations..."):
run_migrations() # a spinner while something slow happensPretty tracebacks are the quiet star. They show the code around each frame and the values of local variables, which often makes the bug obvious without a debugger. Use show_locals in development tools, not where a traceback might print secrets into shared logs.
Match each need to the tool that handles it.
Output for humans and for scripts
Tables and colours are for people. Other programs, such as a CI step, a shell pipeline or a teammate's script, want something they can parse. A common pattern is a --json flag that switches the output format, and an Enum to restrict a value to a fixed set of choices. Typer turns an Enum into a validated option and lists the allowed values in --help. Here is the list command from above, extended with both:
import json
from enum import StrEnum
class Status(StrEnum):
open = "open"
done = "done"
all = "all"
@app.command("list")
def list_todos(
status: Annotated[Status, typer.Option(help="Which todos to show.")] = Status.open,
as_json: Annotated[bool, typer.Option("--json", help="Print JSON instead of a table.")] = False,
) -> None:
"""Show todos."""
todos = repo.list(status=status)
if as_json:
print(json.dumps([t.model_dump() for t in todos])) # plain stdout, no markup
return
console.print(build_table(todos))Now todo list --status done --json | jq length works in a script, and todo list --status finished fails with a message listing the valid choices. Keeping data on stdout and messages on stderr is what makes this composable: a pipeline reads only the data.
Two more small things that make a tool pleasant: typer.prompt("Email") asks for missing input interactively (pass hide_input=True for passwords), and every command should do something sensible with no options at all. When the default is dangerous, make the safe choice the default and the risky one a flag.
What Typer saves you
Under the hood, command-line parsing is fiddly. Here is a slice of the same tool with the standard library's argparse, which Typer replaces. It works, but every option, type and help string is written a second time, separately from the function that uses it.
Press Run (⌘ Enter) to see what happens.argparse is still worth knowing: it has no dependencies, so it is right for a single script you hand to someone else. For a tool your team maintains, Typer's "the function is the interface" approach keeps the two from drifting apart.
Testing a CLI
Typer ships a test runner that calls your app in-process and captures the output and exit code. No subprocesses, no shell.
from typer.testing import CliRunner
from todo.cli import app
runner = CliRunner()
def test_add_rejects_bad_priority():
result = runner.invoke(app, ["add", "Ship it", "--priority", "9"])
assert result.exit_code != 0
def test_export_refuses_to_overwrite(tmp_path):
out = tmp_path / "todos.csv"
out.write_text("old")
result = runner.invoke(app, ["export", "--out", str(out)])
assert result.exit_code == 1Installing it as a real command
Running uv run python src/todo/cli.py gets old quickly. An entry point in pyproject.toml tells Python's packaging tools to create a todo command that calls your app. The project structure lesson in the Python course introduced [project.scripts]; a Typer app is callable, so you point straight at it.
- todo-cli/
- pyproject.tomlname, deps, [project.scripts]
- uv.lock
- src/
- todo/
- __init__.py
- cli.pyapp = typer.Typer()
- repo.pythe real logic
- tests/
- test_cli.pyCliRunner tests
[project]
name = "todo-cli"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = ["typer", "rich"]
[project.scripts]
todo = "todo.cli:app"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"uv init --package todo-cli creates this layout with a build system already set, which is required for the entry point to be installed. Then:
uv run todo --help # inside the project, while developinguv tool install . # install as a global command in its own environmenttodo list # now works from any folderuv tool install --editable . # or: code changes show up without reinstallinguvx --from git+https://github.com/your-org/todo-cli todo list # run once, without installinguv tool install gives each tool its own isolated environment and puts the command on your PATH, so the tool's dependencies never clash with your projects. Teammates can install it straight from your Git repository in the same way.
Put the steps to ship an internal CLI to your team in order.
- Tap the steps below in the right order.
- Typer
- A library that builds command-line interfaces from function signatures and type hints.
- argument
- A positional CLI input, from a parameter with no default:
todo add "Buy milk". - option
- A named CLI input, from a parameter with a default:
--priority 2. - exit code
- The number a program returns to the shell. 0 means success, anything else means failure.
- Rich
- A library for terminal output: markup colours, tables, progress bars and pretty tracebacks.
- entry point
- A
[project.scripts]line that installs a command which calls a Python function or Typer app. - uv tool install
- Installs a Python CLI into its own isolated environment and puts the command on your PATH.