Your terminal applications do not need to have a boring output. Today we take a look at how we can create nice looking tables without much effort.
This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.
Install Rich
Rich is a Python library for rich text and beautiful formatting in the terminal. You can install Rich with this command:
1 |
pip install rich |
If you like what you see in this post, you must take a closer look at the many additional features Rich offers.
Create the table
We need to import the Table and the Console module of Rich to build our table. We can instantiate our table, define the columns and add the rows before we print it to the console:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from rich.console import Console from rich.table import Table table = Table(title="Star Wars Movies") table.add_column("Released", style="cyan", no_wrap=True) table.add_column("Title", style="magenta") table.add_column("Box Office", justify="right", style="green") table.add_row("Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$952,110,690") table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347") table.add_row("Dec 15, 2017", "Star Wars Ep. V111: The Last Jedi", "$1,332,539,889") table.add_row("Dec 16, 2016", "Rogue One: A Star Wars Story", "$1,332,439,889") console = Console() console.print(table, justify="center") |
Rich takes care of everything from calculating the size of the columns to the colouring of the values and creates this output:
All we need to do is to convert values to strings, then the table in Rich does not support any other type. That way we can be as flexible as we want with the conversion to strings and Rich prints out our value exactly as we want.
Colours are optional
If your report needs less colours, you can create your table and ignore all the style attributes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
from rich.console import Console from rich.table import Table report = Table(show_header=True, header_style="bold") report.add_column("Address") report.add_column("City") report.add_column("Postal Code") report.add_row("#500-75 O'Connor Street","Ottawa","K4B 1S2") report.add_row("00, rue Saint-Lazare","Dunkerque","59140") report.add_row("02, place de Fontenoy","Verrieres Le Buisson","91370") console.print(report) |
This creates a much more “professional” looking table that can go into your business application:
Conclusion
Rich is a powerful library to make nice looking console applications. The table is only one of many controls you can use. Therefore, read the documentation and try it on your application!