Python offers an option to print strings in color so that information in the console can be much easier to comprehend. This can be incredible useful when reading long log files, seeing console output, or even creating your own text based adventure games. By using this feature we can print string in different colors and highlights. In this article, we will see this concept thoroughly.
Normally, you can give color to string in python using some prefix in postfix to string. But if you have a facility like different packages or libraries then you can save a lot of time.
Let’s Look At Our Options
There are in fact quite a few packages which are available from python pip which can help you colourize the console. Here is a list of common ones that I’ve found especially useful to add some personality to my console output:
- sty
- colorama
How To Colour Console Output With Python Package: sty
To begin with you can install the package sty as follows:
pip install sty
I am supposing you have any mentioned IDE already installed. So, we are moving towards the practical part.
A sty is a library which is helpful in customizing or decorating string. A sty is short of style and by using this package, you can colorize the foreground and background both. Additionally, you can give some effect to string such as make them italic or bold.
There are mainly four primitives which is used while customizing string which is as follows:
- ef(effect-register)
- fg(foreground-register)
- bg(background-register)
- rs(reset-register)
Each of these primitives has different kinds of default attributes and by using that we can give style to the text. Let’s look at a small example: in which we list out default attributes of ef and fg.
First import the library
from sty import fg, ef, rs, Style, RgbFg,bg, RgbBg
ef_dir=dir(ef)
fg_dir=dir(fg)
print("ef_dir: ",ef_dir)
print("fg_dir: ",fg_dir)
If you have correctly all the things then this thing will work fine and now let’s look at the output of this code snippet. As you can see we have got all default attributes present in both of that module. In ef_dir we have, italic, bold, inverse, and fg has different enlisted colors like blue, black, and many more which we can directly use.
So, yes now we know what’s inside this package. Thus, it’s time to get your hands dirty or colorful using sty.
First, we learn about how to colorize the text and then we focused on the background. Last, we will talk about how to give both effects simultaneously.
To begin with, we will give a red color to your name then we give a yellow background to the same string.
name="Enter your name here" #enter your name here
red_color_string = fg.red + name + rs.fg
print(red_color_string)
As you can see, it’s fairly straight forward code where we gave the red foreground flag then we printed out the text. We also signalled to end this red-colored flag using reset primitive which signals to end whatever we signal earlier as here we give instruction to end foreground color. Otherwise, the red color will be included in all subsequent text.
Let’s add a yellow background now.
yellow_backgroud_string = bg.yellow + name + rs.bg
print(yellow_backgroud_string)
Now, I am putting both of these things together. But with a slight change, as I am changing string color to dark red.
both_effect = fg.da_red + bg.yellow + name + rs.all
print(both_effect)
Yes, your question is correct. Red and yellow are pretty common colors and what if I want to choose some different colors. What about your other color choices. W e can check our color choices too easily using the dir function as we already attached in the output. but we will see that thing again here.
print(dir(fg))
print(dir(bg))
As you can see, you have a wide range as green, blue, light blue, dark blue, cyan, magenta, white present on both of the list. Still not excited? Well, you can input the RGB value and it will give you that color for background and foreground. Let’s try that out.
What you are actually going to do is adding your own color in the fg or bg dictionary and using it later. First, pick some color using google color picker. Just search the color picker in your browser and select any color.
We are choosing color between aqua and green with some dark shade and background as dark pink or maybe you will see when you try it. So, it’s time to look at the code.
fg.text_color = Style(RgbFg(25,209,111)) #RgbFg is foregroundcolor
bg.background_color = Style(RgbBg(204,42,87)) #RgbBg is backgroundcolor
final_output_string = fg.text_color + bg.background_color+ name + rs.all
print(final_output_string)
As you can see the library is pretty flexible since you can even give out a favorite color for text or as background using any RGB values. Thus, you can do so many things using the sty package. The final task we are going to do is give some effects to these texts like making the text bold or underlined.
So, Let’s explore ef primitive and by using that we are going to generate some bold and underlined text as mentioned
bold_text = "This is bold text"
underlined_text = "This is underlined text"
bold_output = ef.bold + fg.text_color + bg.background_color + bold_text + rs.all
underlined_output = ef.underl + fg.da_red + underlined_text + rs.all
print(bold_output,underlined_output,sep='\n')
I hope you all understand all of these three tags completely. You can explore more function of ef primitive using dir and you can generate your own color to customize these strings. So, try out all of these codes and try to minor changes in this code as it will give you a better understanding.
How To Colour Log Output With Python Package: colorama
Colorama works similarly to sty in that you put a start and end tag to colour your console output. In this section, I’ll go one step further and show how it can be setup to also output your log lines in color (you can in fact do the same thing with sty).
So in normal operation, you can colour your text with colorama as follows:
import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello world + Style.RESET_ALL)
Similarly to sty, this will enable you to set the text to BLUE, and then reset the text at the end in order to ensure future text is with the default setting.
You can chose the following foregrounds:
Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
And the following background colors:
Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
And also the following styles:
Style: DIM, NORMAL, BRIGHT, RESET_ALL
So it is pretty straight forward to work with. You will notice that Style has a constant called “RESET_ALL” which can be used to revert and of foreground background or the style.
When it comes to log files, this is the usual setup:
logInst = logging.getLogger("mylog")
logFormatter = logging.Formatter("%(asctime)s %(message)s")
logInst.setLevel(logging.DEBUG)
consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(logFormatter)
logInst.addHandler(consoleHandler)
What this does is to ensure that any calls to logging (e.g. logging.debug) will result in the output going to the console.
Hence, to add color to the console, you simply have to edit the formatter:
logInst = logging.getLogger("mylog")
logFormatter = logging.Formatter(Fore.BLUE + "%(asctime)s [%(filename)s:%(lineno)s - %(funcName)5s() ] [%(levelname)-5.5s] " + Style.RESET_ALL + " %(message)s" )
logInst.setLevel(logging.DEBUG)
consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(logFormatter)
logInst.addHandler(consoleHandler)
The output will show the output as follows – here we’ve added some more useful information in the debug output to make it more readable.
Final Thoughts
All in all, the coloriziation of console is an immensely useful feature and can save some considerable time when looking through log files. Hence, it’s well worth the extra few minutes to set this up.
Subscribe to our newsletter
Error SendFox Connection: