Lesson 29 of 34
Build Polished CLIs with Typer & Rich
A good command-line app has help text, validation, readable , and useful output. Typer and Rich supply those details without burying your actual program.
python -m pip install "typer>=0.12" richfrom pathlib import Path
from typing import Annotated
import typer
from rich.console import Console
from rich.table import Table
app = typer.Typer(help="Inspect text files.", no_args_is_help=True)
console = Console()
@app.command()
def stats(
path: Annotated[Path, typer.Argument(exists=True, dir_okay=False)],
words: Annotated[bool, typer.Option("--words/--no-words")] = True,
) -> None:
"""Show line, word, and character counts."""
text = path.read_text(encoding="utf-8")
table = Table(title=path.name)
table.add_column("Metric")
table.add_column("Count", justify="right")
table.add_row("Lines", str(len(text.splitlines())))
if words:
table.add_row("Words", str(len(text.split())))
table.add_row("Characters", str(len(text)))
console.print(table)
if __name__ == "__main__":
app()python texttool.py --help
python texttool.py stats README.md
# Add a console entry point in pyproject.toml:
# [project.scripts]
# texttool = "texttool:app"
# Then install your project and run it anywhere:
python -m pip install -e .
texttool stats README.mdRich also provides progress bars, syntax highlighting, Markdown rendering, logging handlers, prompts, trees, and improved tracebacks. Keep a plain or output mode for scripts and CI; beautiful output should not make automation brittle.
Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.