Rich Cheat Sheet
Overview
Rich is a Python library for rendering rich text and beautiful formatting in the terminal. It provides tools for styled text, tables, progress bars, syntax highlighting, tracebacks, markdown rendering, tree displays, and much more. Rich works with any terminal that supports ANSI escape codes.
Created by Will McGuigan, Rich has become the de facto standard for building polished CLI applications in Python. It powers the output of tools like Textual, Typer, and many popular Python CLI applications.
Installation
pip install rich
# Verify
python -m rich
Core Usage
Console and Text Styling
from rich.console import Console
from rich.text import Text
console = Console()
# Basic print with markup
console.print("Hello, [bold magenta]World[/bold magenta]!")
console.print("[red]Error:[/red] Something went wrong")
console.print("[green]Success![/green] Deployment complete")
console.print("[italic]Hint:[/italic] Use --help for more info")
# Links
console.print("[link=https://example.com]Click here[/link]")
# Styled text object
text = Text("Hello World")
text.stylize("bold", 0, 5)
text.stylize("red", 6, 11)
console.print(text)
# Emoji support
console.print(":rocket: Deploying... :white_check_mark: Done!")
Tables
from rich.console import Console
from rich.table import Table
console = Console()
table = Table(title="Server Status")
table.add_column("Service", style="cyan", no_wrap=True)
table.add_column("Status", style="green")
table.add_column("Port", justify="right")
table.add_column("Uptime", justify="right")
table.add_row("API Gateway", "[green]Running[/green]", "8080", "14d 3h")
table.add_row("Database", "[green]Running[/green]", "5432", "14d 3h")
table.add_row("Cache", "[yellow]Degraded[/yellow]", "6379", "2h 15m")
table.add_row("Worker", "[red]Stopped[/red]", "N/A", "0s")
console.print(table)
Progress Bars
from rich.progress import Progress, track
import time
# Simple track
for item in track(range(100), description="Processing..."):
time.sleep(0.02)
# Advanced progress
with Progress() as progress:
task1 = progress.add_task("[cyan]Downloading...", total=1000)
task2 = progress.add_task("[green]Installing...", total=500)
while not progress.finished:
progress.update(task1, advance=5)
progress.update(task2, advance=2)
time.sleep(0.02)
Common Components
Panels and Layout
from rich.console import Console
from rich.panel import Panel
from rich.columns import Columns
from rich.layout import Layout
console = Console()
# Panel
console.print(Panel("Hello World", title="Greeting", border_style="green"))
# Panel with rich content
console.print(Panel.fit(
"[bold]Server Info[/bold]\n"
"Host: [cyan]web-01[/cyan]\n"
"Status: [green]healthy[/green]\n"
"Load: [yellow]0.75[/yellow]",
title="Dashboard",
border_style="blue",
))
# Columns
cols = Columns(["Item 1", "Item 2", "Item 3", "Item 4"], equal=True, expand=True)
console.print(cols)
Trees
from rich.tree import Tree
from rich.console import Console
console = Console()
tree = Tree("[bold]Project Structure[/bold]")
src = tree.add("[blue]src/[/blue]")
src.add("[green]main.py[/green]")
src.add("[green]utils.py[/green]")
models = src.add("[blue]models/[/blue]")
models.add("[green]user.py[/green]")
models.add("[green]post.py[/green]")
tests = tree.add("[blue]tests/[/blue]")
tests.add("[green]test_main.py[/green]")
tree.add("[yellow]pyproject.toml[/yellow]")
console.print(tree)
Syntax Highlighting
from rich.console import Console
from rich.syntax import Syntax
console = Console()
code = '''
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10))
'''
syntax = Syntax(code, "python", theme="monokai", line_numbers=True)
console.print(syntax)
# From file
syntax = Syntax.from_path("main.py", line_numbers=True)
console.print(syntax)
Markdown
from rich.console import Console
from rich.markdown import Markdown
console = Console()
md = Markdown("""
# Status Report
## Summary
Everything is **running smoothly**.
## Metrics
- Response time: `45ms`
- Error rate: `0.01%`
- Uptime: `99.99%`
## Next Steps
1. Deploy v2.0
2. Monitor metrics
3. Update documentation
""")
console.print(md)
Configuration
Console Options
from rich.console import Console
# Custom console
console = Console(
width=120,
force_terminal=True,
color_system="truecolor",
record=True,
)
# File output
with open("output.html", "w") as f:
console = Console(record=True)
console.print("[bold red]Error report[/bold red]")
f.write(console.export_html())
# Stderr console
err_console = Console(stderr=True)
err_console.print("[red]Error: connection failed[/red]")
Rich Tracebacks
from rich.traceback import install
# Install rich tracebacks globally
install(show_locals=True)
# Now all exceptions render beautifully
def divide(a, b):
return a / b
divide(1, 0) # Rich traceback with local variables
Logging Integration
import logging
from rich.logging import RichHandler
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
datefmt="[%X]",
handlers=[RichHandler(rich_tracebacks=True)],
)
log = logging.getLogger("rich")
log.info("Server started")
log.warning("High memory usage")
log.error("Connection failed")
Advanced Usage
Live Display
from rich.live import Live
from rich.table import Table
import time
def generate_table(count):
table = Table()
table.add_column("ID")
table.add_column("Status")
for i in range(count):
table.add_row(str(i), "[green]Active[/green]")
return table
with Live(generate_table(0), refresh_per_second=4) as live:
for i in range(20):
time.sleep(0.3)
live.update(generate_table(i + 1))
Prompt and Input
from rich.prompt import Prompt, Confirm, IntPrompt
name = Prompt.ask("Enter your name", default="World")
age = IntPrompt.ask("Enter your age", default=25)
confirm = Confirm.ask("Continue?")
# With choices
color = Prompt.ask("Pick a color", choices=["red", "green", "blue"])
Status Spinners
from rich.console import Console
import time
console = Console()
with console.status("[bold green]Deploying...") as status:
time.sleep(2)
status.update("[bold blue]Running migrations...")
time.sleep(2)
status.update("[bold yellow]Restarting services...")
time.sleep(1)
console.print("[bold green]Deploy complete!")
Inspect Objects
from rich import inspect
inspect(list, methods=True)
inspect("hello", all=True)
Troubleshooting
| Issue | Solution |
|---|---|
| No colors in output | Check terminal supports ANSI; use force_terminal=True |
| Width issues in CI | Set Console(width=120) explicitly |
| Emoji not rendering | Check terminal font supports Unicode |
| Table truncated | Increase console width or use overflow="fold" |
| Progress bar flickering | Reduce refresh_per_second |
| Markup not parsing | Escape brackets with \[ or use highlight=False |
# Debug: check terminal capabilities
from rich.console import Console
console = Console()
console.print(f"Color system: {console.color_system}")
console.print(f"Width: {console.width}")
console.print(f"Is terminal: {console.is_terminal}")