Skip to content

QusaiALBahri/rich-tutorial

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🌈 Rich Library Masterclass: The Complete Tutorial

Make your terminal shine! ✨ Create beautiful, colorful, interactive CLI applications that wow your users. This is THE ultimate guide to mastering Python's rich library.

🎯 What is Rich?

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!

Why You'll Love Rich:

βœ… 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!


πŸ“š Table of Contents

  1. Installation & Setup
  2. Colors & Styling
  3. Text Formatting
  4. Tables - Display Data Like a Pro
  5. Panels & Boxes
  6. Progress Bars
  7. Syntax Highlighting
  8. Console & Output
  9. Markdown Support
  10. Interactive Features
  11. Real-World Applications
  12. Performance Tips
  13. Common Patterns
  14. Troubleshooting

Installation & Setup

Step 1: Create Virtual Environment

# Windows
python -m venv venv
venv\Scripts\activate

# macOS/Linux
python3 -m venv venv
source venv/bin/activate

Step 2: Install Rich

pip install rich

Step 3: Verify Installation

python -c "from rich import print; print('[bold cyan]Rich is installed![/bold cyan]')"

You should see colorful output in your terminal! πŸŽ‰


Colors & Styling

Basic Color Syntax

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]")

Available Colors

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

Example Color Combinations

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)]")

Text Formatting

Emphasis Styles

Style Markup Example
Bold [bold]...[/bold] Bold text
Italic [italic]...[/italic] Italic text
Underline [underline]...[/underline] Underlined
Strike [strike]...[/strike] Strikethrough
Dim [dim]...[/dim] Dimmed text
Blink [blink]...[/blink] Blinking text

Code & Quotes

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]")

Tables - Display Data Like a Pro

Basic Table

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)

Advanced Table Features

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)

Interactive Table Example

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)

Panels & Boxes

Simple Panel

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]"))

Different Box Styles

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))

Create Sections

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"))

Progress Bars

Simple Progress Bar

from rich.progress import track
import time

# Simple progress bar
for i in track(range(100), description="Processing..."):
    time.sleep(0.1)

Advanced Progress Bars

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)

Custom Progress Columns

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)

Syntax Highlighting

Display Code

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)

Supported Languages

Python, JavaScript, Java, C/C++, Go, Rust, etc. (All major languages!)


Console & Output

The Console Object

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)

Export to File

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")

Markdown Support

Render Markdown

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)

Pretty Print (pprint)

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!

Real-World Applications

Check the real-world-apps/ folder for complete, working examples:

1. CLI Task Manager

  • Create, list, and track tasks
  • Color-coded priority levels
  • Progress visualization

2. System Monitor

  • Real-time CPU/Memory display
  • Live progress updates
  • Formatted data tables

3. Log Viewer

  • Beautiful error tracebacks
  • Color-coded log levels
  • Search functionality

4. API Response Viewer

  • JSON formatting
  • Syntax highlighting
  • Table display

5. File Management Tool

  • Tree view of directories
  • File size display
  • Interactive selection

Performance Tips

1. Batch Output

# ❌ 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)

2. Use Segments Wisely

# For massive amounts, use generators
def big_generator():
    for i in range(1000000):
        yield f"[cyan]Line {i}[/cyan]"

console.print(*big_generator())

3. Disable Colors When Not Needed

console = Console(force_terminal=True, legacy_windows=False)

Common Patterns

Error Handling

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!

Status Messages

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]")

Live Display (Real-time Updates)

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)

Troubleshooting

Colors Not Showing

Problem: Terminal shows escape codes instead of colors Solution:

console = Console(force_terminal=True)

UTF-8 Issues (Windows)

Problem: Special characters don't display Solution:

console = Console(legacy_windows=False)

Performance Slow

Problem: Lots of small prints are slow Solution: Use console.print() with multiple arguments or string concatenation

Markup Errors

Problem: [bold] doesn't render Solution: Check matching closing tags [/bold]


Learning Resources


Try It Now! πŸš€

# 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.py

πŸŽ‰ Congratulations!

You 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! 🌈

About

πŸš€ Complete Rich Library Tutorial - 100% Feature Coverage | 40 Examples + 3 Real-World Apps | Jupyter Notebooks | Perfect for Terminal UI Development

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors