Rich

Language: Python

CLI/Utils

Rich was created by Will McGugan in 2019 to bring modern, visually appealing formatting to Python command-line applications. Its goal is to make terminal output more informative, interactive, and beautiful without sacrificing performance or simplicity.

Rich is a Python library for rich text and beautiful formatting in the terminal. It allows you to create colorful and styled console output, including tables, progress bars, markdown, syntax highlighting, and more.

Installation

pip: pip install rich
conda: conda install -c conda-forge rich

Usage

Rich allows developers to print styled text, tables, progress bars, and render markdown in the terminal. It supports colors, gradients, emojis, and live updates for interactive command-line applications.

Printing styled text

from rich import print
print('[bold red]Hello[/bold red] [green]World[/green]!')

Prints 'Hello World!' with 'Hello' in bold red and 'World' in green using Rich's markup syntax.

Creating a table

from rich.console import Console
from rich.table import Table

console = Console()
table = Table(title='Fruits')
table.add_column('Name', style='cyan')
table.add_column('Quantity', justify='right')
table.add_row('Apple', '10')
table.add_row('Banana', '5')
console.print(table)

Creates and prints a styled table with two columns and multiple rows.

Progress bar

from rich.progress import track
import time
for i in track(range(100), description='Processing...'):
    time.sleep(0.05)

Displays a progress bar that updates in real-time as a loop iterates.

Syntax highlighting

from rich.console import Console
from rich.syntax import Syntax

code = 'print("Hello, World!")'
syntax = Syntax(code, 'python', theme='monokai', line_numbers=True)
console = Console()
console.print(syntax)

Displays Python code with syntax highlighting, using the Monokai theme and line numbers.

Live updating panel

from rich.live import Live
from rich.panel import Panel
import time

with Live(Panel('Starting...'), refresh_per_second=4) as live:
    for i in range(5):
        live.update(Panel(f'Progress {i+1}/5'))
        time.sleep(1)

Demonstrates updating terminal content dynamically using Rich's live panels.

Error Handling

ModuleNotFoundError: No module named 'rich': Install Rich using pip or conda in your current Python environment.
Console does not support features: Ensure your terminal supports ANSI colors and UTF-8 encoding for full Rich functionality.

Best Practices

Use Rich for logging, progress bars, and tables to make CLI apps more user-friendly.

Use markup syntax for styling text rather than manual ANSI codes.

Combine Rich with Python’s logging module for structured logs.

Use `Live` and `Progress` for interactive real-time updates.

Leverage Rich themes and styles to maintain consistent CLI design.