Skip to content

Instantly share code, notes, and snippets.

@Turin86
Last active May 12, 2017 07:17
Show Gist options
  • Save Turin86/218c0b878b5fa292642c to your computer and use it in GitHub Desktop.
Save Turin86/218c0b878b5fa292642c to your computer and use it in GitHub Desktop.
Color text based on ANSI color codes
# http://en.wikipedia.org/wiki/ANSI_escape_code
color_code_template = """\x1b[{}m"""
colors = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
color_codes = dict(zip(colors, range(len(colors))))
bold_code = 1
clear_code = 0
def get_code(code):
return color_code_template.format(code)
def get_color_code(color=False, bgcolor=False, hi_fore=False, hi_back=False, bold=False):
codes = []
if bold:
codes.append('1')
if color not in (None, False):
base = 90 if hi_fore else 30
codes.append(str(base + color_codes[color]))
if bgcolor not in (None, False):
base = 100 if hi_back else 40
codes.append(str(base + color_codes[bgcolor]))
return get_code(';'.join(codes))
def get_color_msg(msg, color=None, bgcolor=None, hi_fore=False, hi_back=False, bold=False):
is_colored = any((color, bgcolor, hi_fore, hi_back, bold))
msg = '{}{}{}'.format(
get_color_code(
color=color,
bgcolor=bgcolor,
hi_fore=hi_fore,
hi_back=hi_back,
bold=bold) if is_colored else '',
msg.encode('utf-8') if isinstance(msg, unicode) else msg,
get_code(clear_code) if is_colored else '')
return msg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment