|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +# see also: http://misc.flogisoft.com/bash/tip_colors_and_formatting |
| 4 | + |
| 5 | + |
| 6 | +RESET = 0 |
| 7 | +BLACK = 30 |
| 8 | +RED = 31 |
| 9 | +GREEN = 32 |
| 10 | +BROWN = 33 |
| 11 | +BLUE = 34 |
| 12 | +PURPLE = 35 |
| 13 | +CYAN = 36 |
| 14 | +LIGHT_GRAY = 37 |
| 15 | +_OTHER = 38 |
| 16 | +DEFAULT = 39 |
| 17 | +DARK_GRAY = 90 |
| 18 | +LIGHT_RED = 91 |
| 19 | +LIGHT_GREEN = 92 |
| 20 | +YELLOW = 93 |
| 21 | +LIGHT_BLUE = 94 |
| 22 | +LIGHT_PURPLE = 95 |
| 23 | +LIGHT_CYAN = 96 |
| 24 | +WHITE = 97 |
| 25 | + |
| 26 | +BOLD = 1 |
| 27 | +DIM = 2 # not working on Konsole |
| 28 | +UNDERLINE = 4 |
| 29 | +BLINK = 5 # not working on Konsole and gnome Terminal |
| 30 | +INVERSE = 7 |
| 31 | +HIDDEN = 8 # not working on Konsole |
| 32 | + |
| 33 | +_ESC = '\033' |
| 34 | +_ESC = '\x1b' |
| 35 | +_BACKGROUND = 10 |
| 36 | +_RESET_EFFECT = 10 |
| 37 | + |
| 38 | + |
| 39 | +def colorize(text, color=None, background=None, effects=[], color_256=None, background_256=None, with_end=True): |
| 40 | + start = [] |
| 41 | + end = [] |
| 42 | + |
| 43 | + if color is not None: |
| 44 | + start.append(color) |
| 45 | + end.append(DEFAULT) |
| 46 | + elif color_256 is not None: |
| 47 | + start += [_OTHER, 5, color_256] |
| 48 | + end.append(DEFAULT) |
| 49 | + |
| 50 | + if background is not None: |
| 51 | + start.append(background + _BACKGROUND) |
| 52 | + end.append(DEFAULT + _BACKGROUND) |
| 53 | + elif background_256 is not None: |
| 54 | + start += [_OTHER + _BACKGROUND, 5, background_256] |
| 55 | + end.append(DEFAULT + _BACKGROUND) |
| 56 | + |
| 57 | + for effect in effects: |
| 58 | + start.append(effect) |
| 59 | + end.append(effect + _RESET_EFFECT) |
| 60 | + |
| 61 | + start_code = "%s[%sm" % (_ESC, ';'.join([str(s) for s in start])) if text != '' else '' |
| 62 | + end_code = "%s[%sm" % (_ESC, ';'.join([str(e) for e in end])) if with_end else '' |
| 63 | + return "%s%s%s" % (start_code, text, end_code) |
| 64 | + |
| 65 | + |
| 66 | +def print_colors(): |
| 67 | + color_pivot = [0] |
| 68 | + color_pivot += [e * 6 + 16 for e in range(37)] |
| 69 | + color_pivot.append(256) |
| 70 | + color_pivot_start = color_pivot[:-1] |
| 71 | + color_pivot_end = color_pivot[1:] |
| 72 | + color_table = [range(cs, ce) for cs, ce in zip(color_pivot_start, color_pivot_end)] |
| 73 | + |
| 74 | + for ct in color_table: |
| 75 | + text = '' |
| 76 | + for c in ct: |
| 77 | + cs = str(c) |
| 78 | + padding = ''.join([' ' for e in range(3 - len(cs))]) |
| 79 | + text += colorize(' %s%s ' % (padding, cs), background_256=c, with_end=False) |
| 80 | + print(text + colorize('', background=DEFAULT)) |
| 81 | + |
| 82 | + |
| 83 | +if __name__ == "__main__": |
| 84 | + print_colors() |
0 commit comments