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.
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:
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)
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:
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
- Python Tip for the Week
- Python - Console Improvements - Rich Library
- How Did I Learn Python? What About You?
- F strings in Python - How to use Them?
- Python - Some Things That Make it Unique
- Data Slicing in Python
- Various Ways to Get Data from Python Arrays
- Python Tips: MORE Parsing arguments for your application
- Python Tips: Parsing arguments for your application
- Python Tips: Parsing arguments for your application