Fundor 333's personal space on the web

Color Your Python Output

Reading time 2 minutes
Word count 268
2020-09-10 21:06:21

Sometime you need to output error and other stuff in the same terminal. It can be a lot of text and you need to make more readible for the user/sysadmin/victim so, the easy way, is to make different the output.

The easy way to do it is to color the output to some color.

How it’s work

In the ANSI character set you find the escape code for multiple things: cursor location, color, text style and other option for the terminal and the terminal emulators. So you need to check that your console support the ASCI escape code.

So for using them you need to make inside the string your are outputting, like this

print("\033[91m"+ "I am a red text" + "\033[0m")

red text

You need the string \003[0m for ending the color red (in this case) or the effect you are putting on the string.

This was you need to make every time your string and remember every escape code1.

In my code I use this class

class CLog:
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'

    def error(self,string):

    def info(self,string):

    def debug(self,string):

    def warning(self,string):

In this way I have a colored printer for my little project. If you have a project of medium size or more I suggest to use the module coloredlogs which add color support for the python default logger.

If you choose one of this way you can make more deadible your logger or output for the user.

  1. You can find almost every one of the official escape code on the wikipedia page  ↩︎

If you liked this article,

please share it on

or webmention it

Also on:

IndieWebCamp logo logo