Python Friday #132: Rich Tables for Your Terminal Apps

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:

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:

Rich takes care of everything from calculating the size of the columns to the colouring of the values and creates this output:

A short list of Star Wars movies with the release dates column in blue, the titles in magenta and the revenue in green.

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:

This creates a much more “professional” looking table that can go into your business application:

A basic table with only slight formatting (a bold header)

 

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!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.