Skip to content
Related Articles

Related Articles

Installing and Using Rich Package in Python

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 28 Jun, 2022

In this article, We are going to learn how to install and use rich packages in Python.

RIch is a python package for creating some awesome terminal formatting and logging. It has several features and functions that can make your application look nicer and even add a new look to your CLI application. We will be understanding the process of installing and basic usage of the RICH package in Python in this article.

Installing Rich

Rich is a python package, so we can install it with the pip command, you can directly use the pip install command to install rich but if you don’t want to mess up your global python environment, you can use a virtualenv to try out and play with a package in isolation. So, we will first set up a virtual environment with the virtualenv package 

Setting up a virtual environment

To set up a virtual environment follow the procedure explained in the article Create virtual environment using venv.

To set up a fresh virtual environment, you need the virtualenv package, so install the package globally with the command :

pip install virtualenv

 

This will install virtualenv on your global python environment, so we can now create a virtual environment anywhere on our system. To create a virtual environment, we will use the virtualenv command followed by the name of the virtual environment. Make sure to be in the desired location on your system, the below command will create a directory in the current location.

virtualenv venv

 

So, this will create a fresh virtual environment in your folder, we also need to activate the virtual environment. To activate a virtual environment you need to execute a file called activate depending on your Operation System.

For Linux/macOS:

source venv/bin/activate

 

So this is all we need to create a virtual environment, we can now install any python package in this activated environment.

Using pip to install rich

We can now safely install any packages in our activated virtual environment, to install rich we need to run the following command:

pip install rich

 

This will install rich which is a python package. To verify the installation has been successful, you can run the following command with the help of the python -m command followed by the package name in this case it is Rich.

python -m rich

 

Creating a Python Script to demonstrate Rich

Now, since we have the rich package installed in the virtual environment, we can use the rich package in a python script and leverage its formatting and logging styles in the terminal I/O. We’ll first create a hello word script in python and demonstrate a few other functions and operators provided by the rich package.

Python3




from rich import print
 
print("Hello, [bold green]Geeks[/bold green]!")

 

Here, we are importing a function called print from the rich package which we just installed. The print function is different from the regular print function provided by python. Though it’s technically serving the same purpose it can do a lot more than a normal print function. In the above example, the print function has a few things written which are interpreted by python as a formatting style like the [bold green] and [/bold green]. 

These two tags simply represent the start and end of the styling provided in the square brackets. The styles provided in this example are bold and green. You can choose a few options for the decoration of the text as provided below:

 The colors can be chosen from the list provided in the docs with this link, the colors are 256 Standard colors along with a CSS-styled color format. The decoration like bold, italics, underlined, strike, reverse, etc. can be provided in the list from the documentation. 

Creating an informative tasks display

Python3




from time import sleep
from rich.console import Console
 
console = Console()
tasks = [f"Task {n}" for n in range(1, 8)]
 
with console.status("[bold dark_orange]Finishing tasks...")
as status:
    while tasks:
        task = tasks.pop(0)
        sleep(1)
        console.log(f"{task} complete")

 

The above example shows the process of displaying various tasks in a loop. This is done with the Console Wrapper API. The Console class provides some extended functionalities specifically for terminal content. So, we instantiate a Console object and use the log method to display the output. The status method is used for displaying the ongoing process while being in the loop.  

For more options and functions in the Console class, you can refer to the documentation of the Rich library

Tables in Terminal with Rich

We can even display tables in a rich format with the rich package. The rich package has a way to represent tabular data in the terminal with the Tables class.  We can construct a few sample tables to understand the fundamentals of rendering the tabular data to the console.

Python3




from rich.align import Align
from rich.console import Console
from rich.live import Live
from rich.table import Table
 
TABLE_DATA = [
    [
        "[b white]DSA Course[/]: [i]Beginner[/]",
        "[magenta]$[/]10",
        "[green]Geeks for Geeks[/]",
        "15 hours",
    ],
    [
        "[b white]DSA Course[/]: [i]Intermediate[/]",
        "[magenta]$[/]20",
        "[green]Geeks for Geeks[/]",
        "25 hours",
    ],
    [
        "[b white]DSA Course[/]: [i]Advanced[/]",
        "[magenta]$[/]30",
        "[green]Geeks for Geeks[/]",
        "30 hours",
    ],
    [
        "[b white]Operating System Fundamentals[/]",
        "[magenta]$[/]25",
        "[green]Geeks for Geeks[/]",
        "35 hours",
    ],
]
 
console = Console()
 
 
table = Table(show_footer=False)
table_centered = Align.center(table)
 
console.clear()
 
with Live(table_centered, console=console,
          screen=False):
    table.add_column("Course Name", no_wrap=True)
    table.add_column("Price", no_wrap=True)
    table.add_column("Organization", no_wrap=True)
    table.add_column("Duration", no_wrap=True)
    for row in TABLE_DATA:
        table.add_row(*row)
 
    table_width = console.measure(table).maximum
 
    table.width = None

 

So, here we create a table object with initial adjustments like footer and alignment. The data is first stored as a python list which means you can add or edit the data within itself. By using the function Live, we can create a table on runtime by dynamically adding columns and row values with the add_column and add_row functions in the table class.

The rows or the actual data are added after inserting the columns into the data, by iterating over the previously defined values from the list TABLE_DATA, we can parse the entire row data column-wise. The Live display function is used for displaying the real-time construction of the terminal logs and helps in visualizing the script. 

We can even use the option of the console to simply print the table instead of rendering the table live by the console.log function.

console.print(table)

Rendering Markdown file

We can even render markdown content in the terminal with a simple markdown extension in the rich library in python. Here we will be using a simple markdown file to demonstrate the working of the rich markdown rendering.  The source code sample is provided in the documentation and here we need to make a few changes to make it work.

Python3




from rich.console import Console
from rich.markdown import Markdown
 
console = Console()
with open("sample.md") as readme:
    markdown = Markdown(readme.read())
console.print(markdown)

A sample markdown file has been provided below:

sample.md

# Sample markdown file
Text with some paragraph

2nd paragraph. *Italic*, **bold**, and `monospace`. Itemized lists
look like:

  * this one
  * that one
  * the other one

> Block quotes 

------------

Here's a numbered list:

 1. first item
 2. second item
 3. third item

```python
n = 5
a = "GFG"
for i in range(0, 3): 
  print("Something")
```

### An h3 header ###

Tables can look like this:

size  material      color
----  ------------  ------------
9     leather       brown
10    hemp canvas   natural
11    glass         transparent

Output:

 

Here, we will instantiate the console class since the output will be on the terminal/console. Thereafter we can open the markdown file in the local repository and parse it in the Markdown function that will render the contents and after reading the content of the file we can print the rendered content in the console. 

Trees in Rich

We can also create a tree-like structure in the terminal using Rich. There is a tree class in Rich for displaying hierarchical structures in the terminal, we can create a simple tree instance using the rich tree class.

Python3




from rich.tree import Tree
from rich import print
 
tree_example = Tree("Tree's Root Node")
tree_example.add("Node 1")
print(tree_example)

Output:

 

The tree class is instantiated with the Tree method imported from the rich.tree module. This creates a simple root node in the tree, further, we can add the node into the tree by using the add function associated with the tree. Using this simple code, we can create more styled trees by using the console class in rich.

Python3




# rich-tree.py
from rich.console import Console
from rich.tree import Tree
 
console = Console(width=100)
 
tree = Tree("Programming Languages")
 
python_tree = tree.add("[b green]Python[/]")
python_tree.add("Numpy")
python_tree.add("Pandas")
python_tree.add("Django")
python_tree.add("Flask")
 
java_tree = tree.add("[b dark_orange3]Java[/]")
java_tree.add("Spring")
java_tree.add("Apache")
 
frameworks = ["Express", "React", "Next", "Vue", "Angular"]
js_tree = tree.add("[b yellow]Javascript[/]")
for framework in frameworks:
    js_tree.add(framework)
 
console.print(tree)
 
CONSOLE_HTML_FORMAT = """\
<pre style="font-family:Menlo">{code}</pre>
"""

Output:

 

So in this example, we have used the console class, by adding parameters like width which will set the width of the console and the output screen’s width. Next, we will instantiate a tree class that will create a tree object and stores it in the tree variable, we can name it anything we want as we have named it example_tree in the previous example. As demonstrated earlier we can add nodes to the tree, we will add the node as a new tree, so we will create nested trees. By assigning the returned value of the add function for the tree variable, we have added a new node, we can add nodes further.

Here, the tree variable is the root tree which has nodes like Python, Java, and Javascript with tree class instances as python_tree, java_tree, and js_tree. We have created the python_tree with nodes like Numpy, Pandas, and Django. The java_tree has nodes like Spring and Apache, and finally, we have js_tree nodes as a list of strings which we append dynamically using a for a loop. For each element in the list “frameworks”, we add the nodes in the js_tree.

That’s how we can use the tree class in rich.

Progress Bar in Rich

We can even add progress bars in the terminal using rich. The rich also give a class for displaying progress bars using the track class. The track class gives a view of progress bars until the loop is complete and the given task has reached 100%. 

Python3




from rich.progress import track
from time import sleep
 
for step in track(range(10)):
    sleep(1)

Output:

 

Here, we have demonstrated a basic example of a simple progress bar for a loop that iterates over a range of 10 numbers and it sleeps for a second hence we see the transition of the progress bar.  

We can even perform the task asynchronously and display the progress bar by displaying the love progress.

Python3




import time
 
from rich.progress import Progress
 
with Progress() as progress:
 
    task1 = progress.add_task("[red]Doing Task 1", total=100)
    task2 = progress.add_task("[blue]Doing Task 2", total=40)
    task3 = progress.add_task("[green]Doing Task 3", total=500)
 
    while not progress.finished:
        progress.update(task1, advance=0.1)
        progress.update(task2, advance=0.3)
        progress.update(task3, advance=0.6)
        time.sleep(0.01)

Output:

 

To display a few progress bars on the terminal, we can add use the Progress function in the progress class. We add tasks which are individual progress bars and we increment the current progress, we have included the while loop so that we increment and perform any operation till the progress bar has been completed.

The progress bar is incremented after the task has been performed here the task is simply sleeping for a fraction of a second but that can be any operation like fetching resources from the internet or any other logical operation in the program.

Here, we have added the total parameter in the progress class. The progress class will be displayed, and the task is added by the function add_task which adds a progress bar in the console. The add tasks function takes in the parameter of the task name and the total indicates the number of steps that must be completed for the progress to reach 100%.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!