views:

99

answers:

3

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.

+7  A: 

You could use colorama, but use it sparingly.

leoluk
+1. First time I heard of it, and it works on Windows! I expected it to work on Linux and OS X, but that was a pleasant surprise.
Muhammad Alkarouri
+2  A: 

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'))
unutbu
+1  A: 

Other alternatives are:

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

joaquin