Make your terminal shine! β¨ Create beautiful, colorful, interactive CLI applications that wow your users. This is THE ultimate guide to mastering Python's
richlibrary.
Rich is a Python library that helps you write beautiful text and rich formatting in your terminal. Imagine having access to all the styling power you see in web design, but for your command-line tools!
β Colorful Text - More than 256 colors available β Beautiful Tables - Data presentation made easy β Progress Bars - Track long-running tasks β Syntax Highlighting - Display code beautifully β Emojis & Unicode - Make text expressive β Live Updates - Real-time interactive displays β Error Handling - Beautiful tracebacks β Zero Configuration - Works out of the box!
- Installation & Setup
- Colors & Styling
- Text Formatting
- Tables - Display Data Like a Pro
- Panels & Boxes
- Progress Bars
- Syntax Highlighting
- Console & Output
- Markdown Support
- Interactive Features
- Real-World Applications
- Performance Tips
- Common Patterns
- Troubleshooting
# Windows
python -m venv venv
venv\Scripts\activate
# macOS/Linux
python3 -m venv venv
source venv/bin/activatepip install richpython -c "from rich import print; print('[bold cyan]Rich is installed![/bold cyan]')"You should see colorful output in your terminal! π
Rich uses simple markup in square brackets:
from rich import print
# Color names
print("[red]This text is red[/red]")
print("[blue]This text is blue[/blue]")
print("[green]This text is green[/green]")
# Text styles
print("[bold]Bold text[/bold]")
print("[italic]Italic text[/italic]")
print("[underline]Underlined text[/underline]")
# Combine them!
print("[bold cyan]Bold cyan text[/bold cyan]")
print("[italic yellow]Italic yellow[/italic yellow]")
print("[bold underline red]Bold, underlined, red[/bold underline red]")Standard Colors:
- black, red, green, yellow, blue, magenta, cyan, white
Bright Colors:
- bright_black, bright_red, bright_green, bright_yellow, bright_blue, bright_magenta, bright_cyan, bright_white
256 Color Palette:
[color(196)]for custom colors (0-255)
RGB Colors:
[rgb(255,0,0)]for exact RGB colors
from rich import print
print("[red on white]Red on white background[/red on white]")
print("[italic bold magenta on cyan]Crazy combo![/italic bold magenta on cyan]")
print("[rgb(100,200,255)]Custom RGB color[/rgb(100,200,255)]")| Style | Markup | Example |
|---|---|---|
| Bold | [bold]...[/bold] |
Bold text |
| Italic | [italic]...[/italic] |
Italic text |
| Underline | [underline]...[/underline] |
Underlined |
| Strike | [strike]...[/strike] |
|
| Dim | [dim]...[/dim] |
Dimmed text |
| Blink | [blink]...[/blink] |
Blinking text |
from rich.console import Console
from rich.syntax import Syntax
console = Console()
# Display code with syntax highlighting
code = """
def hello(name):
print(f"Hello, {name}!")
"""
syntax = Syntax(code, "python", theme="monokai", line_numbers=True)
console.print(syntax)
# Quotes
console.print("[bold cyan]\"[/bold cyan]Great minds great thoughts![quote]")from rich.table import Table
from rich import print
table = Table(title="Student Grades")
table.add_column("Name", style="cyan", no_wrap=True)
table.add_column("Subject", style="magenta")
table.add_column("Grade", style="green")
table.add_row("Alice", "Math", "A+")
table.add_row("Bob", "Physics", "B")
table.add_row("Charlie", "Chemistry", "A")
print(table)from rich.table import Table
table = Table(
title="Sales Report 2024",
show_header=True,
header_style="bold white on blue",
row_styles=["none", "dim"] # Alternating row styles
)
table.add_column("Month", style="cyan")
table.add_column("Revenue", justify="right", style="green")
table.add_column("Growth %", justify="right", style="yellow")
table.add_row("January", "$50,000", "β 10%")
table.add_row("February", "$55,000", "β 15%")
table.add_row("March", "$62,000", "β 20%")
from rich import print
print(table)from rich.table import Table
from rich.console import Console
console = Console()
# Create data dictionary
data = {
"Task": ["Build API", "Write Tests", "Deploy", "Document"],
"Status": ["β
Done", "β³ Pending", "β Blocked", "β
Done"],
"Progress": ["100%", "45%", "0%", "100%"]
}
table = Table(title="[bold cyan]Project Status Dashboard[/bold cyan]")
for header in ["Task", "Status", "Progress"]:
table.add_column(header, style="bold")
for i in range(len(data["Task"])):
table.add_row(
data["Task"][i],
data["Status"][i],
data["Progress"][i]
)
console.print(table)from rich.panel import Panel
from rich import print
print(Panel("Welcome to Rich!", title="[bold magenta]Greeting[/bold magenta]"))
print(Panel("[yellow]β οΈ Warning: This is important![/yellow]"))
print(Panel("[green]β
Success! Operation completed.[/green]"))from rich.panel import Panel
from rich.box import *
from rich import print
print(Panel("ROUNDED", box=ROUNDED))
print(Panel("SQUARE", box=SQUARE))
print(Panel("HEAVY", box=HEAVY))
print(Panel("DOUBLE", box=DOUBLE))
print(Panel("ASCII", box=ASCII))from rich.panel import Panel
from rich.console import Console
console = Console()
console.print(Panel("[bold blue]π Project Setup Guide[/bold blue]", expand=False))
console.print()
console.print(Panel("[yellow]Step 1:[/yellow] Create virtual environment", title="Setup", style="yellow"))
console.print()
console.print(Panel("[green]Step 2:[/green] Install dependencies", title="Setup", style="green"))
console.print()
console.print(Panel("[cyan]Step 3:[/cyan] Run your app!", title="Setup", style="cyan"))from rich.progress import track
import time
# Simple progress bar
for i in track(range(100), description="Processing..."):
time.sleep(0.1)from rich.progress import Progress, SpinnerColumn, BarColumn, TextProgressColumn
import time
# Multiple progress bars
with Progress() as progress:
task1 = progress.add_task("[red]Downloading...", total=100)
task2 = progress.add_task("[green]Processing...", total=100)
task3 = progress.add_task("[cyan]Uploading...", total=100)
while not progress.finished:
progress.update(task1, advance=1)
progress.update(task2, advance=0.8)
progress.update(task3, advance=0.5)
time.sleep(0.02)from rich.progress import Progress, BarColumn, TimeRemainingColumn
import time
with Progress(
"[progress.description]{task.description}",
BarColumn(),
"[progress.percentage]{task.percentage:>3.0f}%",
TimeRemainingColumn(),
) as progress:
task = progress.add_task("[cyan]Building...", total=50)
for _ in range(50):
time.sleep(0.1)
progress.update(task, advance=1)from rich.syntax import Syntax
from rich.console import Console
console = Console()
code_str = '''
def greet(name):
"""Function to greet someone"""
message = f"Hello, {name}!"
return message
result = greet("World")
print(result)
'''
syntax = Syntax(
code_str,
"python",
theme="monokai",
line_numbers=True,
background_color="default"
)
console.print(syntax)Python, JavaScript, Java, C/C++, Go, Rust, etc. (All major languages!)
from rich.console import Console
console = Console()
# Basic printing
console.print("Hello World!")
console.print("[bold red]Warning:[/bold red] Something bad happened")
# Styled output
console.print("[on blue white]IMPORTANT[/on blue white]", "Read this!")
# With markup
text = "[bold][cyan]Rich[/cyan] is [yellow]awesome[/yellow]![/bold]"
console.print(text)
# Width and justify
console.print("Centered", justify="center")
console.print("Right aligned", justify="right")
# Highlighting
console.print("Code snippet", highlight=True)from rich.console import Console
# Create console for file output
file_console = Console(file=open("output.html", "w"), record=True)
file_console.print("[bold red]Report Generated[/bold red]")
file_console.save_html("report.html")from rich.markdown import Markdown
from rich.console import Console
console = Console()
markdown_text = """
# Welcome to Rich!
This is a **bold** statement and this is *italic*.
## Features
- π Colors and styles
- π Tables and graphs
- β¨ Beautiful output
```python
print("Code blocks work too!")"""
md = Markdown(markdown_text) console.print(md)
---
## Interactive Features
### Prompts
```python
from rich.console import Console
from rich.prompt import Prompt, Confirm
console = Console()
# Text input
name = Prompt.ask("[bold cyan]What's your name?[/bold cyan]")
console.print(f"[green]Nice to meet you, {name}![/green]")
# Confirmation
confirm = Confirm.ask("[yellow]Continue?[/yellow]")
if confirm:
console.print("[green]Going ahead![/green]")
else:
console.print("[red]Cancelled![/red]")
# Password input (hidden)
password = Prompt.ask("[magenta]Password[/magenta]", password=True)
from rich.console import Console
from rich.pretty import pprint
data = {
"name": "Alice",
"age": 25,
"skills": ["Python", "JavaScript", "Go"],
"projects": {
"web_app": "Flask",
"data_science": "Pandas"
}
}
pprint(data) # Much prettier!Check the real-world-apps/ folder for complete, working examples:
- Create, list, and track tasks
- Color-coded priority levels
- Progress visualization
- Real-time CPU/Memory display
- Live progress updates
- Formatted data tables
- Beautiful error tracebacks
- Color-coded log levels
- Search functionality
- JSON formatting
- Syntax highlighting
- Table display
- Tree view of directories
- File size display
- Interactive selection
# β Slow - Updates one at a time
for item in items:
console.print(item)
# β
Fast - Build once, print once
output = "\n".join(items)
console.print(output)# For massive amounts, use generators
def big_generator():
for i in range(1000000):
yield f"[cyan]Line {i}[/cyan]"
console.print(*big_generator())console = Console(force_terminal=True, legacy_windows=False)from rich.console import Console
from rich.traceback import install
# Install rich traceback handler
install()
console = Console()
try:
result = 10 / 0
except Exception as e:
console.print(f"[bold red]Error:[/bold red] {e}")
console.print_exception() # Beautiful traceback!from rich.console import Console
console = Console()
with console.status("[bold green]Working on tasks..."):
import time
time.sleep(3) # Do work here
console.print("[green]β Done![/green]")from rich.live import Live
from rich.table import Table
import time
table = Table(title="Live Table")
table.add_column("Time", style="cyan")
table.add_column("Status", style="green")
with Live(table, refresh_per_second=2) as live:
for i in range(10):
table.add_row(str(i), "β
OK")
time.sleep(0.5)Problem: Terminal shows escape codes instead of colors Solution:
console = Console(force_terminal=True)Problem: Special characters don't display Solution:
console = Console(legacy_windows=False)Problem: Lots of small prints are slow
Solution: Use console.print() with multiple arguments or string concatenation
Problem: [bold] doesn't render
Solution: Check matching closing tags [/bold]
# Run examples
python examples/01_colors_and_styles.py
python examples/02_tables_demo.py
python examples/03_progress_bars.py
python examples/04_panels_and_boxes.py
python examples/05_syntax_highlighting.py
python examples/06_console_features.py
python examples/07_interactive_prompts.py
python examples/08_live_display.py
python examples/09_markdown_rendering.py
python examples/10_error_handling.py
# Try real-world apps
python real-world-apps/task_manager.py
python real-world-apps/system_monitor.py
python real-world-apps/json_viewer.pyYou now know everything about Rich! Start building amazing CLI applications and watch your terminal glow with color. Your users will love the beautiful experience you create! β¨
Happy Coding! π