pycolib/ansicolor.py
author Radek Brich <radek.brich@devl.cz>
Thu, 04 Apr 2013 20:24:34 +0200
changeset 2 d3ffa15f5886
parent 1 ee31f1bf17c1
child 5 055f7dfb3e4f
permissions -rw-r--r--
Add ColoredFormatter. Add setup.py.

# -*- coding: utf-8 -*-

(BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, BOLD) = range(0,9)

names = ['black','red','green','yellow','blue','magenta','cyan','white']

disabled = False  # set True to disable all colors

def color(enable, fg=None, bg=None):
    '''

    color(1) -- switch to bold, keep previous color
    color(1, RED) -- red foreground
    color(1, BOLD + YELLOW, BLUE) -- yellow on blue, bold
    color(0) -- reset

    '''
    global disabled
    if disabled:
        return ''

    if isinstance(fg, str):
        fg = names.index(fg)
    if isinstance(bg, str):
        bg = names.index(bg)

    if enable:
        code = '1'
        if fg is not None:
            code = ''
            if fg >= 8:
                fg -= 8
                code += '1;'
            code += str(30 + fg)
        if bg is not None:
            code += ';'
            if bg >= 8:
                bg -= 8
                code += '1;'
            code += str(40 + bg)
        return "\033[" + code + "m"
    else:
        return "\033[0m"

def set_color(enable, fg=None, bg=None):
    print(color(enable, fg, bg), end='')


if __name__ == '__main__':
    for c in range(0,8):
        print(
            color(1,c), names[c].ljust(20),
            color(1,8+c), names[c].ljust(20),
            color(0), sep='')