7

Is there a way to print string in colorful way with python?

For example, can I print some part of string red or something to a console? I use Mac OS X.

prosseek
  • 182,215
  • 215
  • 566
  • 871
  • print? Do you mean print to a Linux console? Or print to a Windows console? Or display in an HTML page? What do you mean? – S.Lott Sep 12 '10 at 20:22

4 Answers4

8

You could use colorama, but use it sparingly.

leoluk
  • 12,561
  • 6
  • 44
  • 51
8

This works for linux consoles that support color:

CODE={
    'ENDC':0,  # RESET COLOR
    'BOLD':1,
    'UNDERLINE':4,
    'BLINK':5,
    'INVERT':7,
    'CONCEALD':8,
    'STRIKE':9,
    'GREY30':90,
    'GREY40':2,
    'GREY65':37,
    'GREY70':97,
    'GREY20_BG':40,
    'GREY33_BG':100,
    'GREY80_BG':47,
    'GREY93_BG':107,
    'DARK_RED':31,
    'RED':91,
    'RED_BG':41,
    'LIGHT_RED_BG':101,
    'DARK_YELLOW':33,
    'YELLOW':93,
    'YELLOW_BG':43,
    'LIGHT_YELLOW_BG':103,
    'DARK_BLUE':34,
    'BLUE':94,
    'BLUE_BG':44,
    'LIGHT_BLUE_BG':104,
    'DARK_MAGENTA':35,
    'PURPLE':95,
    'MAGENTA_BG':45,
    'LIGHT_PURPLE_BG':105,
    'DARK_CYAN':36,
    'AUQA':96,
    'CYAN_BG':46,
    'LIGHT_AUQA_BG':106,
    'DARK_GREEN':32,
    'GREEN':92,
    'GREEN_BG':42,
    'LIGHT_GREEN_BG':102,
    'BLACK':30,
}

def termcode(num):
    return '\033[%sm'%num

def colorstr(astr,color):
    return termcode(CODE[color])+astr+termcode(CODE['ENDC'])

if __name__=='__main__':
    astr='yippy skippy'
    # for num in range(300):
    #     color=termcode(num)
    #     print('%s: %s'%(num,color+astr+termcode(CODE['ENDC'])))
    for key in sorted(CODE.keys()):
        print('%s: %s'%(key,colorstr(astr,key)))

    print(colorstr('Red','RED'))

Here is an example of using colorstr to make a colorized logger:

import logging
import copy

logger=logging.getLogger(__name__)

class ColoredFormatter(logging.Formatter):
    # A variant of code found at http://stackoverflow.com/questions/384076/how-can-i-make-the-python-logging-output-to-be-colored
    LEVELCOLOR = {
        'DEBUG': 'BLUE',
        'INFO': 'BLACK',
        'WARNING': 'PURPLE',
        'ERROR': 'RED',
        'CRITICAL': 'RED_BG',
        }

    def __init__(self, msg):
        logging.Formatter.__init__(self, msg)

    def format(self, record):
        record = copy.copy(record)
        levelname = record.levelname
        if levelname in self.LEVELCOLOR:
            record.levelname = colorstr(levelname,self.LEVELCOLOR[levelname])
            record.name = colorstr(record.name,'BOLD')
            record.msg = colorstr(record.msg,self.LEVELCOLOR[levelname])
        return logging.Formatter.format(self, record)

if __name__=='__main__':
    logger.setLevel(logging.DEBUG)
    console = logging.StreamHandler()
    console.setFormatter(
        ColoredFormatter('%(name)s: %(message)s (%(filename)s:%(lineno)d)'))
    logger.addHandler(console)
    fh = logging.FileHandler('/tmp/test.log','w')
    fh.setFormatter(logging.Formatter('%(name)s: %(message)s'))
    logger.addHandler(fh)

    logger.debug('debug')
    logger.info('info')
    logger.warning('Warning')
    logger.error('ERROR')
    logger.critical('CRITICAL!!!')

This example logs to both the console (stderr) and a file (/tmp/test.log). The message to the console is colorized, but the output to the file is left plain.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 1
    Excellent: I would have chosen your solution. Thanks. – neydroydrec Aug 31 '11 at 20:24
  • PS: I both print to console and log to file. On file, the colour tags show up, is there a way to remove them when writing to file by converting the string to some other format? – neydroydrec Aug 31 '11 at 20:40
  • @Benjamin: Are you using the `logging` module, or issuing separate `print` statements (one to the console, one to the file) ? – unutbu Aug 31 '11 at 20:44
  • I made my own logger module using a print statement on screen and a file.write() statement to file. I didn't know a logging module existed. – neydroydrec Sep 01 '11 at 07:49
  • 1
    @Benjamin: I'd recommend switching to the [logging module](http://docs.python.org/library/logging.html) from the standard library. Above, I've posted a little example of how one might log colorized messages to the console, while logging plain messages to a file. – unutbu Sep 01 '11 at 12:39
2

Other alternatives are:

I have played with them in windows. Dont know how they behave in OSX.

joaquin
  • 82,968
  • 29
  • 138
  • 152
1

If you want to do this with minimal effort you could use the tendo.colorer library.

Just by importing it it will color you logging on all platforms, without breaking the redirected log.

Also you could use it to display custom colored messages if you want, as it contains a cross platform ANSI library and a helper for it.

sorin
  • 161,544
  • 178
  • 535
  • 806