Python Rich Library

Click to share! ⬇️

The Python Rich library is a lovely module for displaying rich text with color and style to the terminal and for displaying advanced content such as tables, markdown, and syntax-highlighted code. Python Developers can use Rich to make their command-line applications visually appealing and present data satisfyingly.

Install Python Rich

Rich is straightforward to install using PIP. This simple snippet at the terminal will do the trick for you.

pip install rich

You can see many examples of how the Python Rich Library works in the terminal by viewing examples.

python -m rich

Python Rich Features

  • Colors – 4-bit color ✓ 8-bit color ✓ Truecolor (16.7 million) ✓ Dumb terminals ✓ Automatic color conversion
  • Styles – All ANSI styles: bold, dim, italic, underline, strikethrough, reverse, and even blink.
  • Text – Word wrap text. Justify left, center, correct or full.
  • Asian Language Support – 🇨🇳 该库支持中文,日文和韩文文本!🇯🇵 ライブラリは中国語、日本語、韓国語のテキストをサポートしています 🇰🇷 이 라이브러리는 중국어, 일본어 및 한국어 텍스트를 지원합니다
  • Markup Support – Rich supports a simple BBCode-like markup for color, style, and emoji! 👍 🍎 🐜 🐻 🥖 🚌
  • Tables and Table Data
    Tables     Date           Title                                 Production Budget       Box Office                                                        
              ─────────────────────────────────────────────────────────────────────────────────────────                                                       
               Dec 20, 2019   Star Wars: The Rise of Skywalker           $275,000,000     $375,126,118                                                        
               May 25, 2018   Solo: A Star Wars Story                    $275,000,000     $393,151,347                                                        
               Dec 15, 2017   Star Wars Ep. VIII: The Last Jedi          $262,000,000   $1,332,539,889                                                        
               May 19, 1999   Star Wars Ep. I: The phantom Menace        $115,000,000   $1,027,044,677 
  • Syntax Highlighting
def iter_last(values: Iterable[T]) -> Iterable[Tuple[T, bool]]:
    """Iterate over values, yielding a tuple of the value and a boolean
    indicating whether it is the last value in the iterable.
    """
    it = iter(values)
    try:
        last = next(it)
    except StopIteration:
        return
    for val in it:
        yield last, False
        last = val
    yield last, True
  • Pretty Printing
  • Advanced Inspect

Python Rich print()

Python has a built-in print() function that developers use daily to see their Python programs’ output. The rich library offers an advanced implementation of print() to display output with colors and style in the terminal.

from rich import print

# list of mixed values
my_list = [1, 2, 3, "a", "b", "c"]
print(my_list)

# example dictionary
my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
print(my_dict)

# example tuple
my_tuple = (1, 2, 3, "a", "b", "c")
print(my_tuple)

Python Rich Console

You can use the Console class to gain complete control over terminal formatting.

from rich.console import Console

console = Console()

console.print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", ":coffee:")

Python Rich Text

Now instead of using the console.print() statement with the style command, we can also create a rich-text object and style only this so we can say from rich.text import text, then we create a text object and give it a string, and then we can apply text.stylize() and define the styling, and we can also specify the start and stop index, so now it will apply the styling only to the first six characters.

from rich.console import Console
from rich.text import Text

console = Console()
text = Text("Hello, World!")
text.stylize("bold blue", 0, 6)
console.print(text)

Console Theme

We can also define a theme for our console object by saying from rich.theme import theme, then we create a custom theme, and this is a dictionary where we can give it a name as a key and then different styling as a string. For example, the success theme gets only the styling green, and the error theme gets the styling bold and red. Then we create our console object by giving it this custom theme, and then when we say console.print(), we can apply the different stylings from our theme, so here we use this key success and the key error, and we can also apply it to different parts of the text.

from rich.console import Console
from rich.theme import Theme

custom_theme = Theme({'success': 'green', 'error': 'bold red'})

console = Console(theme=custom_theme)

console.print('That worked!', style='success')
console.print('That failed!', style='error')
console.print('Operation [error]failed[/error]!')

Rich Emoji Markup Language

Python Rich enables us to very easily use emojis by using an emoji markup language so that we can use this thumbs-up markup for the thumbs-up emoji, or here we get an apple and a bug. Still, we can paste them directly here, so let’s run this and see what happens. Here we see we get our thumbs up, and here we have our apple and our bug, so yeah, this is pretty handy to define emojis quickly now instead of using the console.print().

from rich.console import Console
from rich.theme import Theme

console = Console()

console.print(':thumbs_up:', 'Nice work!')
console.print(':apple: :bug: 😀 😃 😄 😁')

Rich Logging

The log() method offers the same capabilities as print but adds some features useful for debugging a running application. Logging writes the current time in a column to the left and the file and line where the method was called to a column on the right.

from rich.console import Console
from rich.theme import Theme

console = Console()

for i in range(10):
    console.log(f"Working on item {i}")

Here is a more advanced example from the official GitHub repo that shows what is possible with the logging available in Python Rich.

"""
A simulation of Rich console logging.
"""

import time
from rich.console import Console
from rich.style import Style
from rich.theme import Theme
from rich.highlighter import RegexHighlighter


class RequestHighlighter(RegexHighlighter):
    base_style = "req."
    highlights = [
        r"^(?P<protocol>\w+) (?P<method>\w+) (?P<path>\S+) (?P<result>\w+) (?P<stats>\[.+\])$",
        r"\/(?P<filename>\w+\..{3,4})",
    ]


theme = Theme(
    {
        "req.protocol": Style.parse("dim bold green"),
        "req.method": Style.parse("bold cyan"),
        "req.path": Style.parse("magenta"),
        "req.filename": Style.parse("bright_magenta"),
        "req.result": Style.parse("yellow"),
        "req.stats": Style.parse("dim"),
    }
)
console = Console(theme=theme)

console.log("Server starting...")
console.log("Serving on http://127.0.0.1:8000")

time.sleep(1)

request_highlighter = RequestHighlighter()

console.log(
    request_highlighter(
        "HTTP GET /foo/bar/baz/egg.html 200 [0.57, 127.0.0.1:59076]"),
)

console.log(
    request_highlighter(
        "HTTP GET /foo/bar/baz/background.jpg 200 [0.57, 127.0.0.1:59076]"
    ),
)


time.sleep(1)


def test_locals():
    foo = (1, 2, 3)
    movies = ["Deadpool", "Rise of the Skywalker"]
    console = Console()

    console.log(
        "[b]JSON[/b] RPC [i]batch[/i]",
        [
            {"jsonrpc": "2.0", "method": "sum",
                "params": [1, 2, 4], "id": "1"},
            {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
            {"jsonrpc": "2.0", "method": "subtract",
                "params": [42, 23], "id": "2"},
            {"foo": "boo"},
            {
                "jsonrpc": "2.0",
                "method": "foo.get",
                "params": {"name": "myself", "enable": False, "grommits": None},
                "id": "5",
            },
            {"jsonrpc": "2.0", "method": "get_data", "id": "9"},
        ],
        log_locals=True,
    )


test_locals()

Rich Inspect

Rich has an inspect() function, which can generate a report on any Python object. It is a fantastic debug aid and an excellent example of the output that Rich can generate. This is an incredible addition to Python and makes understanding your code much more manageable. The example below is a little Meta, as we use the inspect method to inspect the inspect object in Rich.

import rich

rich.inspect(rich.inspect)

Rich Columns

import json
from urllib.request import urlopen

from rich.console import Console
from rich.columns import Columns
from rich.panel import Panel


def get_content(user):
    """Extract text from user dict."""
    country = user["location"]["country"]
    name = f"{user['name']['first']} {user['name']['last']}"
    return f"[b]{name}[/b]\n[yellow]{country}"


console = Console()


users = json.loads(
    urlopen("https://randomuser.me/api/?results=5").read())["results"]
user_renderables = [Panel(get_content(user), expand=True) for user in users]
console.print(Columns(user_renderables))

Rich Trees

from rich.tree import Tree
from rich import print as rprint


tree = Tree("Tree structure")
tree.add("Level 1")
tree.add("Level 1")
tree.add("Level 1").add("Level 2")
tree.add("[red]Level 1").add("[green]Level 2").add("[blue]Level 3")

rprint(tree)

Rich Tables

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

table = Table(title="Todo List")

table.add_column("Number", style="cyan", no_wrap=True)
table.add_column("Todo", style="magenta")
table.add_column("Status", justify="right", style="green")

table.add_row("1", "Learn Rich", "✅")
table.add_row("2", "Practice Python", "✅")
table.add_row("3", "Clean Room", "❌")

console = Console()
console.print(table)

If you’re not using a tool like Rich, the output of your code on the terminal can be a little tedious and challenging to understand. To make it more prominent and prettier, you probably want to use Rich. In this tutorial, we learned how to use Rich to beautify the terminal. There are lots of other features that Rich supports.

Click to share! ⬇️