Created
February 14, 2016 17:21
-
-
Save msikma/2a982e618a7a52ce16fa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# MIT license | |
''' | |
Module for formatting text for display in a terminal. Colored output is | |
provided through the use of ISO 6429 terminal escape sequences. | |
''' | |
# Terminal colors are defined by the ISO 6429 standard. | |
# To convert this list to foreground colors, add 30; | |
# for a background color, add 40. | |
iso_colors = { | |
'black': 0, | |
'red': 1, | |
'green': 2, | |
'yellow': 3, | |
'blue': 4, | |
'purple': 5, | |
'cyan': 6, | |
'white': 7 | |
} | |
# Terminal text effects as defined by the ISO 6429 standard. | |
iso_fx = { | |
'bold': 1, | |
'underline': 4, | |
'blink': 5 | |
} | |
def tprint(string, severity='log'): | |
''' | |
Prints debugging strings to the terminal, colorized according to severity. | |
''' | |
# This function simply calls cprint() with a number of standard arguments | |
# based on the severity of the log. All calls are underlined to distinguish | |
# them from the Flask debugging output. | |
color = None | |
fx = ['underline'] | |
if severity == 'info': | |
color = 'blue' | |
if severity == 'warn': | |
color = 'yellow' | |
if severity == 'error': | |
color = 'red' | |
return cprint(string, color, None, fx) | |
def cprint(string, fgcolor='white', bgcolor=None, fx=[]): | |
''' | |
Prints a colorized string according to a foreground color | |
and optionally a background color and effects list. | |
''' | |
print(cdecorate(string, fgcolor, bgcolor, fx)) | |
def cdecorate(string, fgcolor='white', bgcolor=None, fx=[]): | |
''' | |
Returns a colorized string according to a foreground color | |
and optionally a background color and effects list. | |
''' | |
# Fetch the color numbers, defaulting to white for the foreground. | |
fgcolor = iso_colors.get(fgcolor, None) | |
bgcolor = iso_colors.get(bgcolor, None) | |
# Set the correct foreground and background ISO color values, | |
# and add a semicolon to the background color if it has been set. | |
if fgcolor is not None: | |
fgcolor += 30 | |
if bgcolor is not None: | |
bgcolor += 40 | |
# Modify the effects list so that it contains ISO values | |
# instead of the alias. | |
fx = [str(iso_fx[n]) for n in fx if n in iso_fx] | |
# Separate the colors with a semicolon if we've set both of them. | |
colors = [str(n) for n in (bgcolor, fgcolor) if n is not None] | |
colors = ';'.join(colors) | |
# Same goes for the effects. | |
fx = ';' + ';'.join(fx) if fx is [] else '' | |
# Return the decorated string. | |
return '\033[%s%sm%s\033[0m' % (colors, fx, string) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment