4th Street Bar Hive-Bar

Hive-Bar Powered by Hive beta-fdb5b5b

Community post

Python - Console Improvements - Rich Library

https://snipboard.io/icvPrl.jpg

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!

29 upvotes $0.14

Replies (6)

Review before signing

Posting as . Signing with . Keychain permission: Posting. Hive Keychain will ask you to approve this action next.


  
Technical details

Operation fingerprint: