Hi Pythonistas!
Today we will learn about a new module called rich. Rich is a python library for writing rich text to console. It helps us to write colorful text, tables and progress bars in the terminal. Let us dive into the code
Installation
pip install rich
Showing rich text in terminal
from rich.console import Console
console = Console()
console.print("Hello, [bold red]world[/bold red]!")
console.print("This is [italic underline blue on yellow]rich![/italic underline blue on yellow]")
Here in first print the hello will be normal text but world will be bold and red in color
Here in second print This is will be a normal text but rich will be in italic, has underline, color of text will be blue and background will be yellow
Showing table in console
from rich.console import Console
from rich.table import Table
console = Console()
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Name", style="bold")
table.add_column("Age", style="italic", width=12)
table.add_column("Occupation")
table.add_row("Abcd Efg", '30', "Software Engineer")
table.add_row("Hightk Lmn", '25', "Data Scientist")
console.print(table)
Here we defined a table with columns name, age and occupation. The header font will be bold and color will be magenta, for the Age column we have added italics. When we print this we get a table in the console
Showing progress bar in console
import time
from rich.progress import Progress
with Progress() as progress:
task1 = progress.add_task("[red]Downloading...", total=1000)
task2 = progress.add_task("[green]Processing...", total=1000)
task3 = progress.add_task("[cyan]Cooking...", total=1000)
while not progress.finished:
progress.update(task1, advance=0.5)
progress.update(task2, advance=0.3)
progress.update(task3, advance=0.9)
time.sleep(0.1)
This code sets up a progress bar with three tasks: Downloading, Processing, and Cooking. Each task has a specified color (red, green, and cyan, respectively). The progress bar runs in a loop until all tasks are finished. Inside the loop, the progress.update() method is called for each task to update their progress. The advance parameter determines how much the progress advances for each update.
Rich can be used to make your terminal more beautiful if you are mainly working on these kinds of projects.
I hope you have learned something from this post please share your valuable suggestions with afsal@parseltongue.co.in