Saturday, March 13, 2021

Colorizing Text with Python

 

Let me tell you a story, a story of struggles and challenges, a drab colorless life until one day a gleaming figure steps out of the mist and introduces me to the rainbow of colors that are......

Actually, it's just a short post of how to add a little color to your Python console output.

Let's start with a class definition, one that defines the escape key sequences necessary for adding color to simple text.  The general format is encapsulating the text within a start and end key sequence.  The string starts with a header, followed by the color sequence, then the actual string, followed by a trailer sequence that indicates we're done with the key sequence.

 

$ cat -n Color.py
     1    #!/usr/bin/python
     2   
     3    class Color:
     4      Header='\033[95m';
     5      Trailer='\033[0m';
     6      Default      = '\033[39m';
     7      Black        = '\033[30m';
     8      Red          = '\033[31m';
     9      Green        = '\033[32m';
    10      Yellow       = '\033[33m';
    11      Blue         = '\033[34m';
    12      Magenta      = '\033[35m';
    13      Cyan         = '\033[36m';
    14      LightGray    = '\033[37m';
    15      DarkGray     = '\033[90m';
    16      LightRed     = '\033[91m';
    17      LightGreen   = '\033[92m';
    18      LightYellow  = '\033[93m';
    19      LightBlue    = '\033[94m';
    20      LightMagenta = '\033[95m';
    21      LightCyan    = '\033[96m';
    22      White        = '\033[97m';
    23   
    24      Bold='\033[1m';
    25      Underline='\033[4mm';
    26   
    27      @staticmethod
    28      def colorize(val,color):
    29        colorVal=eval('Color.%s'%(color));
    30        retVal="%s%s%s%s"%(Color.Header,colorVal,val,Color.Trailer);
    31        return retVal;

 

The 'colorize' method takes in a string and a color, returns a string sequence. As an alternative, you can use the key sequences explicitly.  This short example demonstrates both possibilities.

 $ cat -n foo
     1    #!/usr/bin/python
     2    #-- https://godoc.org/github.com/whitedevops/colors
     3    
     4    from Color import Color;
     5    
     6    print "Using explicit control characters";
     7    print " " + Color.Header + Color.Red + "Red" + Color.Trailer;
     8    print " " + Color.Header + Color.Green + "Green" + Color.Trailer;
     9    print " " + Color.Header + Color.Blue + "Blue" + Color.Trailer;
    10    
    11    for color in ['Black', 'Red', 'Green', 'Yellow' , 'Blue', 'Magenta', 'Cyan', 'LightGray', 'DarkGray', 'LightRed', 'LightGreen', 'LightYellow', 'LightBlue', 'LightMagenta', 'LightCyan', 'White']:
    12      print " > %s"%(Color.colorize(color,color));
    13    


Now, go slap some color in your boring old programs!


 

No comments:

Post a Comment