Skip to content

Instantly share code, notes, and snippets.

@TheWaWaR
Created July 22, 2016 06:59
Show Gist options
  • Save TheWaWaR/4c7604ac56a524d5484c11fe9b70d8fb to your computer and use it in GitHub Desktop.
Save TheWaWaR/4c7604ac56a524d5484c11fe9b70d8fb to your computer and use it in GitHub Desktop.
Mini termcolor
# coding: utf-8
"""ANSII Color formatting for output in terminal. (termcolor-1.1.0)"""
import os
ATTRIBUTES = dict(list(zip(['bold', 'dark', '', 'underline',
'blink', '', 'reverse', 'concealed'],
list(range(1, 9)))))
del ATTRIBUTES['']
HIGHLIGHTS = dict(list(zip(['on_grey', 'on_red', 'on_green', 'on_yellow',
'on_blue', 'on_magenta', 'on_cyan', 'on_white'],
list(range(40, 48)))))
COLORS = dict(list(zip(['grey', 'red', 'green', 'yellow',
'blue', 'magenta', 'cyan', 'white'],
list(range(30, 38)))))
RESET = '\033[0m'
def colored(text, color=None, on_color=None, hl=None, attrs=None):
"""
Available text colors:
red, green, yellow, blue, magenta, cyan, white.
Available text highlights:
on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.
Available attributes:
bold, dark, underline, blink, reverse, concealed.
Example:
colored('Hello, World!', 'red', 'on_grey', ['blue', 'blink'])
colored('Hello, World!', 'green')
"""
if os.getenv('ANSI_COLORS_DISABLED') is None:
fmt_str = '\033[%dm%s'
if color is not None:
text = fmt_str % (COLORS[color], text)
if (on_color or hl) is not None:
text = fmt_str % (HIGHLIGHTS[on_color or hl], text)
if attrs is not None:
for attr in attrs:
text = fmt_str % (ATTRIBUTES[attr], text)
text += RESET
return text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment