Display Rich Text In The Console Using Python

Jigahuhu
6 min readNov 30, 2020

Are you using the terminal more than GUI-based operating systems? Or, do you usually develop command-line interface programs using Python? Recently, I found an amazing Python library called “Rich” on GitHub, which already has 15.2k stars by the time I’m writing this article.
It can not only display text in colour and styles in the terminal but also emoji, tables, progress bars, markdown and even syntax highlighted code. If you have read one of my previous articles below:
5 Interesting Python Libraries
Have you ever think data visualisation can be in command-line?
towardsdatascience.com
The “Rich” library can almost do everything that I have introduced in that article, as well as some other awesome stuff.
In this article, I’ll introduce this library with examples to show its capabilities.
Introduction & Installation
Image for post
Image source: https://github.com/willmcgugan/rich (Official GitHub README.md)
The image above shows the major features that the library can do. You can find the project on GitHub:
willmcgugan/rich
Rich is a Python library for rich text and beautiful formatting in the terminal. The…
github.com
The library requires Python 3.6.1 or above to be functional. Installing the library is quite simple because we can use pip.
pip install rich
Rich Printing
Let’s first look at how it can print.
Tags and Emoji
It supports formatting tags and emoji.
from rich import print
print(“Hello, [bold blue]Towards Data Science[/bold blue]!”, “:thumbs_up:”, “[u]By[/u]”, “[i]Christopher Tao[/i]”)
Image for post
Syntax Highlight
It can also automatically format a dictionary and highlight Python keywords and outputs. For example, let’s output the local environment in Python using the locals() method.
Image for post
The above example shows the difference between the output with and without the rich library.
Rich REPL
We can also install Python REPL using the rich library so that any data structures can be printed and highlighted based on the standards.
from rich import pretty
pretty.install()
{“bool1”:True, “bool2”:False, “number”:123.45, “string”:”Hello!”, “dict”:{“key”:”value”}, “list”:[1,2,3], “class”:type(1)}
Image for post
Pretty Print Documentation of Classes/Methods
You may know that we can use __doc__ and help() methods to display documentation of a Python class/object/method. However, it is hard to read in the terminal.
str.__doc__
help(str)
Image for post
Image for post
By using the Rich library, we can use its inspect() function to pretty-print the above documentation.
from rich import inspect
inspect(str, methods=True)
Image for postImage for post
The flag methods will decide whether the methods are displayed in the documentation. If true, it is equivalent to help(). Otherwise, it is equivalent to __doc__.
Syntax Highlight of Python Code
I guess you won’t be surprised that the library can print code with syntax highlighted because we can kind of see the feature in the previous example.
Let me just illustrate it using a simple example. Below is just a random piece of code in my gist.
from rich.console import Console
from rich.syntax import Syntax
code_snippet = ‘’’
def max_vote_recursive(states, days_left, index):
# Terminating conditions
if len(states) == 0 or index >= len(states) or days_left <= 0:
return 0
# If we have enough days, go to this state
votes_if_go = 0
if states[index][‘days’] <= days_left:
votes_if_go = states[index][‘votes’] + max_vote_recursive(states, days_left — states[index][‘days’], index + 1)
# If we don’t go to this state
votes_if_not_go = max_vote_recursive(states, days_left, index + 1)
return max(votes_if_go, votes_if_not_go)
‘’’
syntax = Syntax(code_snippet, “python”, line_numbers=True)
console = Console()
console.print(syntax)
Image for post
It’s like in a GUI-based IDE, super cool!
Advanced Printing Using Console Object
The Rich library also provides a module called “Console” that enables more customised styles of prints and some features out-of-box. We can import the module and instantiate the object as follows.
from rich.console import Console
console = Console()
For example, the log() method of a console object can print a “log style” output on the screen.
console.log(“We are using”, console, “!”)
Image for post
Please note that the time is automatically added in the logs.
The console object also has a flag log_locals that can be a very useful debugging tool. It outputs all the local variables currently in the memory.
console.log(“All local variables”, log_locals=True)
Image for post
Integrate with Logging Library
Python has a built-in logging library which is utilised for displaying logs with different levels and formats. The Rich library can seamlessly integrate with the library to provide a further pretty-print experience.
Let’s import the logging library and initialise the log object first.
import logging
from rich.logging import RichHandler
FORMAT = “%(message)s”
logging.basicConfig(
level=”NOTSET”, format=FORMAT, datefmt=”[%X]”, handlers=[RichHandler()]
)
log = logging.getLogger(“rich”)
Then, we can output some logs to see what happen.
log.debug(“Debug Message.”)
log.info(“Info Message.”)
log.warning(“Warning Message.”)
log.error(“Error Message.”)
log.fatal(“Fatal Message.”)
Image for post
Very cool, our logs will be coloured in the terminal now.
Python Traceback Beautifier
I was really amazed by this feature. I’m sure you’ll, too. The Rich library can show the traceback of any expectation in a very readable way. This feature is out-of-box that is actually a combination of all of the above features.
To illustrate all the elements of the pretty traceback, we need to have relatively complex code. So, please allow me to use the screenshot from the official GitHub readme page.
Image for postImage for post
Image source: https://github.com/willmcgugan/rich (Official GitHub README.md)
Rich Tables
The Rich library can also display a table very beautifully. More importantly, the style and word-wraps will be automatically adjusted based on the width of the terminal window.
Here is a code snippet that can generate a table using the Rich library. Eventually, it will be printed.
from rich.console import Console
from rich.table import Table
console = Console()
table = Table(show_header=True, header_style=”bold magenta”)
table.add_column(“Date”, style=”dim”, width=12)
table.add_column(“Title”)
table.add_column(“Production Budget”, justify=”right”)
table.add_column(“Box Office”, justify=”right”)
table.add_row(
“Dev 20, 2019”, “Star Wars: The Rise of Skywalker”, “$275,000,000”, “$375,126,118”
)
table.add_row(
“May 25, 2018”,
“[red]Solo[/red]: A Star Wars Story”,
“$275,000,000”,
“$393,151,347”,
)
table.add_row(
“Dec 15, 2017”,
“Star Wars Ep. VIII: The Last Jedi”,
“$262,000,000”,
“[bold]$1,332,539,889[/bold]”,
)
console.print(table)
Image for postImage for post
As above-mentioned, the table will fit the current width of the terminal window to make sure that the table is displayed perfectly.
Image for postImage for post
Rich Progress Bars
The Rich library also provides amazing progress bar feature. The usage is also extremely simple.
from rich.progress import track
from time import sleep
for step in track(range(100), description=”Writing Medium Story…”):
sleep(0.1)
Image for postImage for post
Of course, the progress bar is very flexible that can be customised with a lot of aspects such as displaying multiple progress bars together and detailed progress label text as follows.
Image for post
gif source: https://github.com/willmcgugan/rich (Official GitHub README.md)
Image for post
gif source: https://github.com/willmcgugan/rich (Official GitHub README.md)
Rich Markdown
The Rich library can also display markdown text in the terminal.
I’ve created a sample markdown file beforehand. Then, we can import the Markdown module in the Rich library to display it.
from rich.console import Console
from rich.markdown import Markdown
console = Console()
with open(“test.md”) as md:
markdown = Markdown(md.read())
console.print(markdown)
Image for post
Although it cannot display the headers in different font sizes because of the limitation of the terminal, it still can distinguish them using different styles.
Summary
Image for post
Photo by Engin_Akyurt on Pixabay
OK. Please allow me to stop here. There are just too many impressive features in this library that I can’t show them all in one article, though I have demonstrated the ones that I think are the most interested. There are still more features such as the columns, panel, padding and render groups that are also great. It is highly recommended to check them out by yourself.
The GitHub Repo and official documentation are as follows. Happy coding!. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

--

--