AI Skill Report Card
Building Rich CLI Interfaces
Quick Start15 / 15
Pythonfrom rich.console import Console from rich.progress import Progress from rich.table import Table import time console = Console() # Basic colored output console.print("Hello [bold green]World[/bold green]!") # Simple progress bar with Progress() as progress: task = progress.add_task("[cyan]Processing...", total=100) for i in range(100): time.sleep(0.01) progress.update(task, advance=1) # Basic table table = Table(title="Results") table.add_column("Name", style="cyan") table.add_column("Status", style="green") table.add_row("Task 1", "✓ Complete") console.print(table)
Recommendation▾
Add installation command (pip install rich) in Quick Start section
Workflow13 / 15
Step 1: Setup Rich Console
Pythonfrom rich.console import Console from rich.logging import RichHandler import logging console = Console() # Setup rich logging logging.basicConfig( level="INFO", format="%(message)s", handlers=[RichHandler(console=console)] ) log = logging.getLogger("rich")
Step 2: Create Progress Tracking
Pythonfrom rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn def create_progress(): return Progress( SpinnerColumn(), TextColumn("[progress.description]{task.description}"), BarColumn(), "[progress.percentage]{task.percentage:>3.0f}%", TimeElapsedColumn(), console=console )
Step 3: Build Data Tables
Pythonfrom rich.table import Table def create_table(title, data): table = Table(title=title, show_header=True, header_style="bold magenta") if data: # Add columns from first row keys for key in data[0].keys(): table.add_column(key.title(), style="cyan") # Add rows for row in data: table.add_row(*[str(v) for v in row.values()]) return table
Step 4: Implement Status Display
Pythonfrom rich.status import Status from rich.panel import Panel def show_status(message): with console.status(f"[bold green]{message}..."): # Your processing code here time.sleep(2)
Recommendation▾
Include error handling patterns and how to gracefully degrade when Rich features aren't supported
Examples18 / 20
Example 1: File Processing CLI
Pythonfrom rich.console import Console from rich.progress import Progress, track from rich.table import Table from rich.panel import Panel import os import time console = Console() def process_files(directory): files = [f for f in os.listdir(directory) if f.endswith('.txt')] # Show file count console.print(Panel(f"Found {len(files)} files to process", title="Info")) results = [] # Process with progress bar for file in track(files, description="Processing files..."): time.sleep(0.1) # Simulate processing size = os.path.getsize(os.path.join(directory, file)) results.append({"File": file, "Size": f"{size} bytes", "Status": "✓"}) # Show results table table = Table(title="Processing Results") table.add_column("File", style="cyan") table.add_column("Size", style="yellow") table.add_column("Status", style="green") for result in results: table.add_row(result["File"], result["Size"], result["Status"]) console.print(table) # Usage process_files("./data")
Example 2: System Monitor Dashboard
Pythonfrom rich.console import Console from rich.table import Table from rich.progress import Progress, BarColumn, TextColumn from rich.layout import Layout from rich.live import Live import psutil import time console = Console() def create_dashboard(): layout = Layout() layout.split_column( Layout(name="header", size=3), Layout(name="body"), Layout(name="footer", size=3) ) layout["header"].update(Panel("System Monitor", style="bold blue")) layout["footer"].update(Panel("Press Ctrl+C to exit", style="dim")) return layout def update_stats(): # CPU Usage cpu_table = Table(title="CPU Usage") cpu_table.add_column("Core", style="cyan") cpu_table.add_column("Usage", style="yellow") for i, percent in enumerate(psutil.cpu_percent(percpu=True)): cpu_table.add_row(f"Core {i}", f"{percent:.1f}%") # Memory Usage memory = psutil.virtual_memory() memory_table = Table(title="Memory") memory_table.add_column("Type", style="cyan") memory_table.add_column("Value", style="yellow") memory_table.add_row("Total", f"{memory.total / 1024**3:.1f} GB") memory_table.add_row("Used", f"{memory.used / 1024**3:.1f} GB") memory_table.add_row("Free", f"{memory.free / 1024**3:.1f} GB") memory_table.add_row("Usage", f"{memory.percent:.1f}%") return Group(cpu_table, memory_table) # Live dashboard layout = create_dashboard() with Live(layout, refresh_per_second=1, screen=True): for _ in range(60): # Run for 60 seconds layout["body"].update(update_stats()) time.sleep(1)
Example 3: Download Progress with Multiple Tasks
Pythonfrom rich.progress import Progress, DownloadColumn, TransferSpeedColumn import time import random def download_files(urls): with Progress( TextColumn("[progress.description]{task.description}"), BarColumn(), "[progress.percentage]{task.percentage:>3.0f}%", DownloadColumn(), TransferSpeedColumn(), ) as progress: tasks = [] for url in urls: filename = url.split('/')[-1] file_size = random.randint(1000000, 10000000) # Simulate file size task = progress.add_task(f"[cyan]{filename}", total=file_size) tasks.append((task, file_size)) # Simulate downloads while not all(task.finished for task in progress.tasks): for task_id, total_size in tasks: if not progress.tasks[task_id].finished: chunk_size = random.randint(10000, 100000) progress.update(task_id, advance=chunk_size) time.sleep(0.1) # Usage urls = [ "https://example.com/file1.zip", "https://example.com/file2.pdf", "https://example.com/file3.exe" ] download_files(urls)
Recommendation▾
Expand completeness with more edge cases like handling very long text, terminal resizing, and performance considerations for large datasets
Best Practices
- Use consistent color schemes: Stick to cyan for headers, green for success, red for errors
- Combine multiple Rich features: Use Progress + Console + Tables together for comprehensive UIs
- Handle terminal width: Rich auto-adjusts, but test on narrow terminals
- Use markup sparingly:
[bold green]text[/]for emphasis, not decoration - Implement graceful fallbacks: Rich degrades nicely on unsupported terminals
Common Pitfalls
- Don't mix print() with Rich: Always use
console.print()for consistent formatting - Avoid blocking operations in Live updates: Use threading for heavy computations
- Don't nest Progress contexts: Create separate progress instances instead
- Remember to close Live displays: Use context managers or explicit
.stop() - Don't over-animate: Too many spinners/progress bars reduce readability