Home Python How to Format Terminal Using Python’s Rich Library

How to Format Terminal Using Python’s Rich Library

Python Rich Library is a great library for writing text with color and style them in the terminal. It can be used to display tables, markdowns, progress bars, and syntax-highlighted code in the terminal. Though the library is not too old and the first version was released on 10 November 2019, it gained high popularity in the python community and Github. When writing this post, the library had achieved 13.3k stars in GitHub, and it keeps increasing.

If you are a command-line lover like most Linux users including me, then the Rich library will be handy for you and your python projects. To work with Rich Library, we need to have python installed and set up its path in the system.

Installing Rich in Python

Rich can be installed on Linux, OS X, and Windows operating systems, making its code portable, unlike other formatting libraries that have limitations to work only with one platform. For Linux, it gives good performance on formatting the terminal. Still, for windows users, they must use the new window terminal available in the windows store instead of using a command prompt to get all the features of the rich.

It requires Python 3.6.1 or above to work with. We can easily install rich in python using the pip packed manager. To do so, type the following command in the terminal.

pip install rich

We can also install it from the anaconda cloud by typing the following command.

conda install -c conda-forge rich

Now, let us see how we can use it to format our Linux terminal beautifully. You can check the installation by running the following code in a python shell.

import rich

If the code runs without any error, then the rich is successfully installed in your system.

Quick Demo of Rich Library

Let us look at a quick demo of using the rich library and how it makes our terminal beautiful. Just copy the following code and run it into your favorite Python IDE.

# importing the rich library
from rich import print
# print Hello in italic and red color
print("[italic red]Hello[/italic red] World!")

If everything is okay with your python and rich installation, the output may be seen as in the below image.

demo of rich library

demo of the rich library

In the above program, we have imported the print() of the rich library, which can be used as an alternative to the print() function present in python. To remove any confusion with the python print() function, we can import the print() function of the rich library as rprint and use rprint() while formatting instead of print. Example:

from rich import print as rprint
rprint("[italic red]Hello[/italic red] World!")

It is a good practice to use the print() function of the rich library as a print(), so we will not get confused with the python’s built-in print() function. On running the code, we will get the same output as in the previous code. We can also use the rich print function to print emojis. For example, run the following code.

from rich import print as rprint
rprint("[i]Hello[/i] [bold red]World[/]! :smiley: ")

Output:

printing emoji using rich library

printing emoji using a rich library

The Console API

For full control over terminal formatting, the rich library provides a Console class. We can use the console class by using the following piece of code.

from rich.console import Console
# creating the console object
console = Console()

The console object handles all the mechanics for generating ANSI escape sequences for color and style. It will also auto-detect the terminal capabilities we were using and convert colors if necessary, which will benefit for cross-platform applications. There is also a print() function in the Console class, which we can use to print the style components. The Rich library will convert any objects to a string with its (__str__) method. It will also give style to any containers, such as dictionaries and lists when output in the terminal. Example:

from rich.console import Console
# creating a console object
console = Console()
# displaying a python list
console.print([10, 12, 13])
# creating a python dictionary
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
console.print(car)
# displaying a link
console.print("https://www.codeunderscored.com/")

You will see that the printed list and dictionary and link have been colored on running the above code, as shown in the below image.

printing data structure using the rich library

printing data structure using the rich library

Logging using Rich

The Rich library provides an amazing log() function which can be used for logging. The log() function provides the same capabilities as the print() function and adds some additional features useful for debugging applications. Logging writes the current time in a column on the left and writes the file and line where the method was called to a column on the right. Hence it will be useful for debugging applications for errors. Let us see an example of how to log using the Console class’s log() function in the rich library. Copy and run the following code in a Python IDE.

from rich.console import Console
# creating the console object
console = Console()
# using the log() method of the console object
console.log("Hello, World!")

Output:

logging using rich

logging using rich

In the output, you may see that the time is display on the left, and the file name and line numbers are also displayed on the right. It’s handy for debugging code. We can also use the rich library to justify-content. Both the print() and the log() function of the console class support a justify argument which can be set to one of the “default”, “left”, “right”, “center”, or “full”. The “left” argument will place the text on the left side of the terminal. The “right” argument will place the text on the right side of the terminal, and the “center” argument will place the text in the center of the terminal. For a Demo, copy and run the following code in your favorite python IDE.

# important required modules
from rich import print
from rich.console import Console
# creating the console object
console = Console()
# displaying the text by justifying
console.print("This is the Default", )
console.print("This is justify left", justify="left")
console.print("This is justify center", justify="center")
console.print("This is justify right", justify="right")

Output:

justify text using rich

justify the text using rich

As you can see in the output, all the texts are justified to the center.

The Input() method

The Console class has an input() method that acts as same as the python’s built-in input() method. But we can use all the rich formatting in the input() function of the Console class. For a practical demo, run the following code in your favorite python IDE.

from rich.console import Console
console = Console()
console.input("What is [i]your[/i] [bold red]name[/]? :smiley: ")

Output: It is almost like the python’s built-in input() function but with some of Rich Library’s added functionalities.

input function of rich library

input function of the rich library

Exporting and Saving the Rich Text

Rich’s Console class also has support to save anything written using it as text or Html. To do so, we need to set record=True in the console class, and after doing the formatting, use the save_text() or save_html() methods to write the contents directly to disk. To see how it works, copy the following code into a python IDE, and run it.

# importing the required modules
from rich import print
from rich.console import Console
# creating the console objectwith record set to true
console = Console(record=True)
print("[italic red]Hello[/italic red] World!")
console.print([10, 12, 13])
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
console.print(car)
console.print("https://www.codeunderscored.com/")
console.log("Hello, World!")
console.input("What is [i]your[/i] [bold red]name[/]? :smiley: ")
# saving all the formatted text in a html file
console.save_html("hello.html")

This code will save all the output performed using the console object into an HTML file named hello.html. You can see the file present in the current working directory. You can open this file with your preferred browser to view the contents.

Styling The Terminal

To make our command-line applications beautiful, we need to style them with colors and other styling techniques. The rich library provides an easy to use way to style the programs. We can use the style tag of the print() function of the Console class to style an object. For example, if we want to print the string “Hello World” in the red color, we have to write the following code.

from rich.console import Console
console = Console()
console.print("Hello World", style="red")

This code will print the string “Hello World” in red color on the terminal. We can also give the color hexadecimal value, as shown in the below code.

from rich.console import Console
console = Console()
console.print("Hello World", style="#8a8a8a")

This will print the string “Hello World” in the color of hex value #8a8a8a. We can also give the background color of a text using the style tag. For example, see the following.

from rich.console import Console
console = Console()
console.print("Hello World", style="red on white")

This code will print the string “Hello World” with red color and white background color. We can also give the arguments “bold”, “italic,” or  “underline” in the style tag of the print() function as shown in the below code.

from rich.console import Console
console = Console()
console.print("Hello World", style="red bold underline on white")

Output:

styling using rich

styling using rich

We can also display a link in the terminal by using the style tag. We need to use the link argument, followed by the link we want to give. Run the below code in your python IDE to see how it works.

from rich.console import Console
console = Console()
console.print("Codeunderscored", style="link https://codeunderscored.com")

This code will print the link output as Codeunderscored on the terminal.

Tables

Rich also provides a Table class that gives many ways to display tabular data on the terminal. Let us see how we can use it to build beautiful tables in Console using python. To print a table, we need to add columns and rows using the add_columns() and add_rows(), respectively, and then print them in the console.

Example:

# importing the required classes from the rich module
from rich.console import Console
from rich.table import Table

# creating the table object
table = Table(title="Employee Details")

# adding the columns
table.add_column("EmpID", style="cyan", no_wrap=True)
table.add_column("Name", style="magenta")
table.add_column("Age", justify="right", style="green")

# adding the rows
table.add_row("1001", "David", "35")
table.add_row("1098", "Sam", "41")
table.add_row("2001", "Ayush", "33")
table.add_row("1980", "Sam", "32")

# creating the console object
console = Console()

# displaying the table using the console object
console.print(table)

Output:

printing tables using rich library

printing tables using the rich library

Let us see how the above code works. In the first two lines, we imported the console and table classes from the rich module, which would be required for creating and displaying tables. Then on the next line, we use the Table() class to create a table object. We also give the title to the table using the title parameter of the Table() class. In the next few lines, we use the add_columns() method of the Table() class to add columns.

It accepts the style parameter that can be used to color the tabular data of that column. Then we add rows in the table using the add_rows() method of the Table() class. While doing so, notice that we have added three columns, so we give three arguments to the add_rows() method. For more columns, we need to give more arguments. Finally, we use the console object to display the table in the Terminal.

Markdown

We can also use the rich library of python to render markdown in the console. We need to use the Markdown class of the rich library to render markdown in the terminal. Markdown is a great way to use rich text easily. They are used in websites, documentation, Github, and many more. Let us look at an example to display markdown in the terminal.

from rich.console import Console
from rich.markdown import Markdown

MARKDOWN = """
# This is a heading(h1)
## This is a sub heading(h2)
This is **bold** and this is *italic*
1. This is a list item
2. This is another list item

[This is a link](https://www.codeunderscored.com)

```
# this is a code block
import python
```
"""

console = Console()
md = Markdown(MARKDOWN)
console.print(md)

In the first line of the above code, we create a multiline string of markdown text and store it in a variable named MARKDOWN. Then we use the Markdown class to compile the markdown text and displayed it to the console.

Output:

displaying markdown using rich library

displaying markdown using a rich library

If you want to learn more about the syntax of markdown and how it is helpful, you can follow the official GitHub markdown tutorial.

Conclusion

In this tutorial, we have learned to use the python rich library to format the terminal easily. Although I have covered the rich library’s important concepts, there are many more tasks we can do with the rich library. You can refer to the official documentation of the rich to learn more about it.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More