In this tutorial we will be exploring Rich – a python package for working with rich text and beautiful formatting in the terminal or command prompt.
First of all let see some of the benefits we can do with this package.
- Adding Color and Style to Text
- Emoji
- Markdown
- Syntax Highlighting
- Tables In the Terminal
Rich can be very useful when building CLI especially when you want to add some beautification to your CLI, you can check out more on how to building CLI and the many ways we can make your CLI fancy here.
Let us see how to work with rich.
Installation
pip install rich
Rich requires another packages called commonmark. Hence if you do not have it you can also install it along side rich
Adding Color and Style To Text
First of all let us import the package
from rich.console import Console
You can then create a Console instance and store it inside a variable to use if for your task
console = Console()
Using Console().print()
You can add colors to text in two ways using the style format or the span format
# Text/Color console.print("Hello world",style='bold red') console.print("[u]Hello[/u] [bold cyan]Jesse[/bold cyan]")
Using print
You can also import a custom print function from rich which will overide the normal python print function
from rich import print print("Hello [bold magenta]Jesse[/bold magenta]")
Working with Emojis
With rich you can display emojis or their unicode in your terminal.
# Emoji console.print("I :heart: coding :smiley:")
Rendering Markdown in the Terminal
You can render markdown inside the terminal using the Markdown from the rich.markdown submodule. This is where you may need the commonmark if not installed already on your system.
from rich.markdown import Markdown # Markdown with open("README.md") as md: markdown = Markdown(md.read()) console.print(markdown)
Displaying Code Syntax
from rich.syntax import Syntax my_code = """ def hello(name): return "Hello {}".format(name) """ # Syntax synt = Syntax(my_code,"python",theme='monokai',line_numbers=True) console.print(synt)
Showing Tables in the Terminal
With rich you can also display nice tables in your terminal
from rich.table import Table,Column table = Table(show_header=True,header_style="bold cyan") # Define Column table.add_column("Title",style="dim",width=12) table.add_column("Author",style="dim",width=12) # Add your Data into the Rows table.add_row("Python Handbook","Wes Mickn") console.print(table)
Of course there are a lot of things you can do with Rich, you can check their docs for more.
You can also check the video tutorial below for more
Thank you for your attention
Jesus Saves
Jesse E.Agbe(JCharis)