Pages

Monday, January 26, 2026

News : examples with rich python package.

Python's Rich package is a tool kit that helps you generate beautifully formatted and highlighted text in the console.
Let's see some examples:
Run the source code with these args --demo and --dashboard:
import time
import sys
import logging
import argparse
import msvcrt  # Windows keyboard input

from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn
from rich.syntax import Syntax
from rich.layout import Layout
from rich.live import Live
from rich.theme import Theme
from rich.logging import RichHandler

# ---------------------------------------------------------
# 1. DARK THEME
# ---------------------------------------------------------
dark_theme = Theme({
    "info": "bold cyan",
    "warning": "bold yellow",
    "error": "bold red",
    "success": "bold green",
    "title": "bold magenta",
    "data": "bold white",
})

console = Console(theme=dark_theme)

# ---------------------------------------------------------
# 2. LOGGING (RichHandler)
# ---------------------------------------------------------
logging.basicConfig(
    level="INFO",
    format="%(message)s",
    datefmt="[%H:%M:%S]",
    handlers=[RichHandler(console=console)]
)
log = logging.getLogger("CLI")

# ---------------------------------------------------------
# 3. CLI ARGUMENTS
# ---------------------------------------------------------
def parse_args():
    parser = argparse.ArgumentParser(
        description="Rich CLI + Dashboard + Menu + Buttons"
    )
    parser.add_argument("--demo", action="store_true", help="Run the demo")
    parser.add_argument("--dashboard", action="store_true", help="Start the dashboard")
    return parser.parse_args()

# ---------------------------------------------------------
# 4. WINDOWS KEY READER
# ---------------------------------------------------------
def get_key():
    if msvcrt.kbhit():
        return msvcrt.getch().decode(errors="ignore")
    return None

# ---------------------------------------------------------
# 5. MENU + BUTTONS
# ---------------------------------------------------------
menu_items = ["Statistics", "Processes", "Settings", "Exit"]
selected = 0

def render_menu():
    table = Table(show_header=False, expand=True)
    for i, item in enumerate(menu_items):
        if i == selected:
            table.add_row(f"[black on cyan] {item} [/]")
        else:
            table.add_row(f"[cyan] {item} [/]")
    return Panel(table, title="Menu", border_style="cyan")

def render_content():
    if menu_items[selected] == "Statistics":
        return Panel("CPU: 37%\nRAM: 62%\nDisk: 128MB/s", title="System Statistics")

    elif menu_items[selected] == "Processes":
        return Panel("proc1\nproc2\nproc3", title="Running Processes")

    elif menu_items[selected] == "Settings":
        return Panel("Settings will appear here", title="Settings")

    elif menu_items[selected] == "Exit":
        return Panel("[red]Press ENTER to exit[/red]", title="Exit")

# ---------------------------------------------------------
# 6. DASHBOARD LAYOUT (original + menu added)
# ---------------------------------------------------------
def build_dashboard():
    layout = Layout()

    layout.split(
        Layout(name="header", size=3),
        Layout(name="body", ratio=1),
        Layout(name="footer", size=3),
    )

    layout["body"].split_row(
        Layout(name="left", size=30),
        Layout(name="right")
    )

    layout["header"].update(
        Panel("[title]LIVE DASHBOARD — Rich Dark Mode[/title]", style="bold magenta")
    )

    layout["left"].update(render_menu())
    layout["right"].update(render_content())

    layout["footer"].update(
        Panel("[info]Status: Running in real time[/info]")
    )

    return layout

# ---------------------------------------------------------
# 7. DEMO (unchanged from first script)
# ---------------------------------------------------------
def run_demo():
    console.print("[success]Rich Dark Mode Demo Started[/success]")

    table = Table(title="Example Table", expand=True)
    table.add_column("ID", style="yellow")
    table.add_column("Name", style="cyan")
    table.add_column("Status", style="green")

    table.add_row("1", "Catalin", "Active")
    table.add_row("2", "Rich CLI", "OK")
    table.add_row("3", "Dashboard", "Ready")

    console.print(table)

    log.info("This is an INFO message")
    log.warning("This is a WARNING message")
    log.error("This is an ERROR message")

    with Progress(
        SpinnerColumn(),
        BarColumn(),
        TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
        console=console,
    ) as progress:
        task = progress.add_task("Processing...", total=100)
        for _ in range(100):
            time.sleep(0.02)
            progress.update(task, advance=1)

    code = """
def greet(name):
    return f"Hello, {name}!"

print(greet("Catalin"))
"""
    syntax = Syntax(code, "python", theme="monokai", line_numbers=True)
    console.print(Panel(syntax, title="Syntax Highlight"))

# ---------------------------------------------------------
# 8. MAIN LOOP
# ---------------------------------------------------------
if __name__ == "__main__":
    args = parse_args()

    if args.demo:
        run_demo()

    if args.dashboard:
        with Live(build_dashboard(), refresh_per_second=10) as live:
            while True:
                key = get_key()

                if key == "w":
                    selected = (selected - 1) % len(menu_items)
                elif key == "s":
                    selected = (selected + 1) % len(menu_items)
                elif key == "\r":
                    if menu_items[selected] == "Exit":
                        break

                live.update(build_dashboard())