Skip to content

Python Rich: Simplifying Console Output for Effortless and Enhanced Visualizations

[

The Python Rich Package: Unleash the Power of Console Text

Python’s Rich package is a tool kit that helps you generate beautifully formatted and highlighted text in the console. More broadly, it allows you to build an attractive text-based user interface (TUI).

Why would you choose a TUI over a graphical user interface, or GUI? Sometimes a text display feels more appropriate. Why use a full-blown GUI for a simple application, when an elegant text interface will do? It can be refreshing to work with plain text. Text works in almost any hardware environment, even on an SSH terminal or a single-board computer display. And many applications don’t need the complexity of a full graphical windowing system.

In this tutorial, you’ll learn how Rich can help you:

  • Enhance the user interface of command-line tools
  • Improve the readability of console output
  • Create attractive dashboard displays for real-time tabular data
  • Generate well-formatted reports

Will McGugan, the author of Rich, has also developed the Textual package. Whereas Rich is a rich-text tool kit, Textual is a full application framework built on Rich. It provides application base classes, an event-driven architecture, and more.

There’s a lot you can do with Rich on its own, and its support for engaging, dynamic displays may well be sufficient for your app. By following this tutorial, you’ll experiment with many of the cool features of Rich, and you’ll finish up by using your skills to build a dynamically scrolling tabular display of crypto prices.

To fully understand Rich’s syntax for animations, you should have a good grasp of context managers. But if you’re a bit rusty, don’t worry! You’ll get a quick refresher in this tutorial.

Installing Rich

You can start using Rich very quickly. As always when starting a new project or investigation, it’s best to create a virtual environment first, to avoid polluting your system’s Python installation.

It’s quite possible to install Rich and use it with the built-in Python REPL, but for a better developer experience, you may want to include support for Jupyter notebooks. Here’s how you can install Rich so that it’ll work with either the REPL or Jupyter:

  • Windows PowerShell:
PS> python -m venv rich-tutorial
PS> .\rich-tutorial\Scripts\activate
(rich-tutorial) PS> python -m pip install -U rich
  • Linux + macOS:
$ python -m venv rich-tutorial
$ source rich-tutorial/bin/activate
(rich-tutorial) $ python -m pip install -U rich

Using Rich for Python Development

Once you have Rich installed, you can start using it to enhance your Python development experience. Let’s explore some of the key features of Rich:

Syntax Highlighting

One of the standout features of Rich is its ability to highlight syntax in the console. This makes it easier to read and understand your code when working in a text-based environment.

To highlight syntax with Rich, simply import the Syntax class and use it to create a syntax-highlighted code block. Here’s an example:

from rich import print
from rich.syntax import Syntax
python_code = '''
def greet(name):
print(f'Hello, {name}!')
greet('World')
'''
print(Syntax(python_code, "python", theme="monokai", line_numbers=True))

Code Object Inspection

Rich also provides a way to inspect code objects and display detailed information about them in a formatted manner. This can be helpful when debugging or exploring Python objects.

To inspect a code object with Rich, use the inspect function. Here’s an example:

from rich import inspect
def add(a, b):
return a + b
inspect(add)

The Console Class

The Console class in Rich is the main entry point for creating custom console applications. It provides a flexible and powerful way to create text-based user interfaces.

To create a console application with Rich, simply create an instance of the Console class and use its various methods to render text, colors, tables, and more. Here’s an example:

from rich.console import Console
console = Console()
console.print("Hello, World!", style="bold green")

Logging and Tracebacks

Rich also improves the logging experience in Python by providing a RichHandler that outputs logs in a more readable and attractive format. It also enhances tracebacks with syntax highlighting and additional context.

To use Rich for logging, add the RichHandler to your logger configuration. Here’s an example:

import logging
from rich.logging import RichHandler
logger = logging.getLogger(__name__)
logger.addHandler(RichHandler())
logger.info("This is an informational log message")
logger.error("An error occurred")

Keeping Your User Engaged Through Animation

A great way to enhance the user experience in a text-based interface is through animations. Rich provides several features to create and display dynamic animations in the console.

Understanding Context Managers

Context managers are a key concept in Python that allow for resource management and cleanup. They can also be used to create animations by displaying dynamic content within a defined context.

To create an animation with Rich, use the animator context manager. Here’s an example:

from rich.console import Console
from rich.progress import Progress
console = Console()
with console.status("Loading..."):
for task in console.track(range(100)):
task.update(progress=task.completed + 1, description="Processing...")

Displaying Dynamic Status With Animations

Rich provides the Status class to create dynamic status animations that display real-time updates. This can be useful for showing progress, status messages, or any other changing information.

To create a status animation with Rich, create an instance of the Status class and update its attributes as needed. Here’s an example:

from rich.console import Console
from rich.status import Status
console = Console()
status = Status("Processing...")
console.print(status)
status.start()
# Perform some processing...
status.update("Still processing...")
# Continue processing...
status.stop()

Animating Activities With Progress Bars

Another way to engage users in a text-based interface is by using progress bars. Rich provides the Progress class to create and update progress bars in real time.

To create a progress bar with Rich, create an instance of the Progress class and use its update method to increment the progress. Here’s an example:

from rich.progress import Progress
progress = Progress()
task = progress.add_task("Processing...", total=100)
for i in range(100):
progress.update(task, advance=1)

Bringing Tables to Life

Tables are a great way to display tabular data in a text-based interface. Rich provides the Table class to create and customize tables, including features like sorting and filtering.

Building a Static Table

To create a static table with Rich, create an instance of the Table class and use its add_column method to define the columns. Here’s an example:

from rich.console import Console
from rich.table import Table
console = Console()
table = Table(show_header=True, header_style="bold")
table.add_column("Name", style="dim", width=12)
table.add_column("Age", style="dim", width=8)
table.add_column("Location", style="dim", width=20)
table.add_row("John Doe", "30", "New York")
table.add_row("Jane Smith", "25", "London")
table.add_row("Bob Johnson", "35", "Paris")
console.print(table)

Animating a Scrolling Display

Rich also allows you to create scrolling displays for tables, which can be useful for displaying large amounts of tabular data in a limited space.

To create a scrolling table with Rich, use the scrollable=True option when creating the Table instance. Here’s an example:

from rich.console import Console
from rich.table import Table
console = Console()
table = Table(show_header=True, header_style="bold", scrollable=True)
table.add_column("Name", style="dim", width=12)
table.add_column("Age", style="dim", width=8)
table.add_column("Location", style="dim", width=20)
for i in range(100):
table.add_row(f"Name {i}", f"Age {i}", f"Location {i}")
console.print(table)

Accessing the Crypto Data

In this tutorial, you’ll use the rich.box style to create a visually appealing table for displaying real-time cryptocurrency prices. The data will be fetched from the CoinGecko API using the requests library, and the prices will update every few seconds.

Here’s a summary of the steps involved in accessing the crypto data and coding the live table:

  1. Import the required libraries (requests, datetime, and time)
  2. Create a function to fetch the crypto prices from the CoinGecko API
  3. Initialize the Table instance with the appropriate column names
  4. Create a loop to continuously update the prices and display the live table using the console.print method

Conclusion

The Python Rich package provides a powerful set of tools for generating beautifully formatted and highlighted text in the console. With Rich, you can enhance the user interface of your command-line tools, improve the readability of console output, create attractive dashboard displays for real-time tabular data, and generate well-formatted reports.

In this tutorial, you learned how to install Rich, use it for Python development, and create engaging animations, dynamic status displays, and interactive tables. Rich offers a wide range of possibilities for creating visually appealing and interactive text-based user interfaces.

Next Steps