Agile Automation avatar

Python - Console Improvements - Rich Library

agileautomation

Published: 16 Jan 2024 › Updated: 16 Jan 2024Python - Console Improvements - Rich Library

Python - Console Improvements - Rich Library

All python developers will be using the console to print out messages or debug info at times in their development and some of these consoles can be running continuously, with many messages.

Being able to format and color highlight these is a NICE way to improve our scripts and to highlight specific messages which is easily done with the "Rich" library.

Rich allows you to use rich text formatting in the terminal and its super easy to use!

pip install rich

You can simply import the print function from the rich library and print will now be color syntax highlighting automatically for you with all its other features. It still uses the same inputs as the built in print, so its compatible with anything you already have written.

from rich import print

Color Syntax Highlighting

If you then print an object or data element, rich colors things nicely for you.

image.png

image.png

Justification

from rich.console import Console

console = Console(width=20)

style = "bold white on blue"
console.print("Rich", style=style)
console.print("Rich", style=style, justify="left")
console.print("Rich", style=style, justify="center")
console.print("Rich", style=style, justify="right")
This produces the following output:

Rich
Rich                
        Rich        
                Rich

Creating progress bars

from rich.progress import track
 
for num in track(range(100)):
    print(num * 2)
    time.sleep(0.1)

More Examples:

image.png

Table Formatting

This is a really powerful feature and hard to do with terminal output directly, so this is an impressive feature of rich.

from rich.table import Table
from rich.console import Console
 
table = Table("First table using rich!")
table.add_column("Language", justify="right", style="bright_yellow", no_wrap=True)
table.add_column("Year Initially Released", style="green")
table.add_column("Most recent version", justify="right", style="red")
 
table.add_row("", "Python", "1991", "3.9.1")
table.add_row("", "R", "1993", "4.0.3")
table.add_row("", "Java", "1995", "Java 15")
 
console = Console()
console.print(table)

image.png

What have you used Rich to do with your scripts?

I hope you found some useful tips here and that you go try out rich with your python applications!

Leave Python - Console Improvements - Rich Library to:

Written by

A software consultant specializing in control systems, automation and data collection. Python Development and tips.

Read more #python posts


Best Posts From Agile Automation

We have not curated any of agileautomation's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Agile Automation