Tables in Terminal with Rich
We can even display tables in a rich format with the rich package. The rich package has a way to represent tabular data in the terminal with the Tables class. We can construct a few sample tables to understand the fundamentals of rendering the tabular data to the console.
Python3
from rich.align import Align from rich.console import Console from rich.live import Live from rich.table import Table TABLE_DATA = [ [ "[b white]DSA Course[/]: [i]Beginner[/]" , "[magenta]$[/]10" , "[green]Geeks for Geeks[/]" , "15 hours" , ], [ "[b white]DSA Course[/]: [i]Intermediate[/]" , "[magenta]$[/]20" , "[green]Geeks for Geeks[/]" , "25 hours" , ], [ "[b white]DSA Course[/]: [i]Advanced[/]" , "[magenta]$[/]30" , "[green]Geeks for Geeks[/]" , "30 hours" , ], [ "[b white]Operating System Fundamentals[/]" , "[magenta]$[/]25" , "[green]Geeks for Geeks[/]" , "35 hours" , ], ] console = Console() table = Table(show_footer = False ) table_centered = Align.center(table) console.clear() with Live(table_centered, console = console, screen = False ): table.add_column( "Course Name" , no_wrap = True ) table.add_column( "Price" , no_wrap = True ) table.add_column( "Organization" , no_wrap = True ) table.add_column( "Duration" , no_wrap = True ) for row in TABLE_DATA: table.add_row( * row) table_width = console.measure(table).maximum table.width = None |
So, here we create a table object with initial adjustments like footer and alignment. The data is first stored as a python list which means you can add or edit the data within itself. By using the function Live, we can create a table on runtime by dynamically adding columns and row values with the add_column and add_row functions in the table class.
The rows or the actual data are added after inserting the columns into the data, by iterating over the previously defined values from the list TABLE_DATA, we can parse the entire row data column-wise. The Live display function is used for displaying the real-time construction of the terminal logs and helps in visualizing the script.
We can even use the option of the console to simply print the table instead of rendering the table live by the console.log function.
console.print(table)
Installing and Using Rich Package in Python
In this article, We are going to learn how to install and use rich packages in Python.
RIch is a python package for creating some awesome terminal formatting and logging. It has several features and functions that can make your application look nicer and even add a new look to your CLI application. We will be understanding the process of installing and basic usage of the RICH package in Python in this article.