Python print colored message on command line terminal window

When you are developing a python script with some output messages printed on the terminal window, you may find a little bit boring that all the messages are printed in black and white, especially if some messages are meant for warning, and some just for information only. You may wonder how to use different colors to make them look differently, so that your users are able to pay special attention to those warning or error messages.

In this article, I will be sharing with you a library which allows you to print your output messages in different colors.

Let’s get started!

The library I am going to introduce called colorama, which is a small and clean library for coloring your messages in both Windows, Linux and Mac os.

Prerequisite

You will need to install this library, so that you will be able to run the following code in this article.

To start using this library, you will need to import the modules, and call the init() method at the beginning of your script or your class initialization method.

The init method also accepts some **kwargs to overwrite it’s default behaviors. E.g. by default, the style will not be reset back after printing out a message, and the subsequent messages will be following the same styles. You can pass in autoreset = true to the init method, so that the style will be reset after each printing statement.

Below are the options you can use when formatting the font, background and style.

To use it in your message, you can do as per below to wrap your messages with the styles:

This is how it would look like in your terminal:

As I mentioned earlier, if you don’t set the autoreset to true, you will need to reset the style at the end of your each message, so that different message applies different styles.

What if you want to apply the styles when asking user’s input ? Let’s see an example:

By wrapping the input inside Fore.YELLOW and Style.RESET_ALL, whatever output messages from your script or user entry, the same style will be applied.

Let’s put all the above into a script and run it in the terminal to check how it looks like.

Yes, that’s exactly what we want to achieve! Now you can wrap your printing statement into a method e.g.: print_colored_message, so that you do not need to repeat the code everywhere.

As per always, please share if you have any comments or questions.

Original post from: https://www.codeforests.com

Resources and tutorials for python, data science and automation solutions