2 min read

Python Rich Library

Rich is a Python library for rich text and beautiful formatting in the terminal. It supports colors, styles, tables, progress bars, markdown, syntax highlighted source code, and tracebacks.

Installation

pip install rich

Basic Printing

The easiest way to use Rich is to import the print function. It supports BBCode-like tags.

from rich import print

print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals())
print("[italic red]Error[/italic red]: Something went wrong!")

The Console Object

For more control, use the Console object.

from rich.console import Console

console = Console()
console.print("Hello", style="bold blue")
console.print("Danger!", style="bold red on white")

Tables

Rich can render flexible tables with unicode box characters.

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

console = Console()

table = Table(title="Star Wars Movies")

table.add_column("Released", justify="right", style="cyan", no_wrap=True)
table.add_column("Title", style="magenta")
table.add_column("Box Office", justify="right", style="green")

table.add_row("Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$952,110,690")
table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347")
table.add_row("Dec 15, 2017", "Star Wars Ep. VIII: The Last Jedi", "$1,332,539,889")

console.print(table)

Progress Bars

Rich provides a very easy way to add progress bars to loops using track.

from rich.progress import track
import time

for step in track(range(100), description="Processing..."):
    time.sleep(0.05)

Inspecting Objects

Rich has an inspect function that produces a beautiful report on any Python object.

from rich import inspect

my_list = ["foo", "bar"]
inspect(my_list, methods=True)

Syntax Highlighting

Rich can syntax highlight code snippets.

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

code = """
def hello(name):
    print(f"Hello {name}")
"""

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

programming/python/python