Skip to content

Instantly share code, notes, and snippets.

@sheljohn
Last active July 27, 2024 09:05
Show Gist options
  • Save sheljohn/68ca3be74139f66dbc6127784f638920 to your computer and use it in GitHub Desktop.
Save sheljohn/68ca3be74139f66dbc6127784f638920 to your computer and use it in GitHub Desktop.
Print with colors in most shells (Python, standalone)
# Python 2, class
# Author: J.Hadida (jhadida87 at ggooglemail)
class ColorPrinter:
"""
Usage:
cprint = ColorPrinter()
cprint.cfg('c','m','bux').out('Hello','World!')
cprint.rst().out('Bye now...')
See: http://stackoverflow.com/a/21786287/472610
See: https://en.wikipedia.org/wiki/ANSI_escape_code
"""
COLCODE = {
'k': 0, # black
'r': 1, # red
'g': 2, # green
'y': 3, # yellow
'b': 4, # blue
'm': 5, # magenta
'c': 6, # cyan
'w': 7 # white
}
FMTCODE = {
'b': 1, # bold
'f': 2, # faint
'i': 3, # italic
'u': 4, # underline
'x': 5, # blinking
'y': 6, # fast blinking
'r': 7, # reverse
'h': 8, # hide
's': 9, # strikethrough
}
def __init__(self):
self.rst()
# ------------------------------
# Group actions
# ------------------------------
def rst(self):
self.prop = { 'st': [], 'fg': None, 'bg': None }
return self
def cfg(self,fg,bg=None,st=None):
return self.rst().st(st).fg(fg).bg(bg)
# ------------------------------
# Set individual properties
# ------------------------------
def st(self,st):
if isinstance(st,int):
assert (st >= 0) and (st < 10), 'Style should be in {0 .. 9}.'
self.prop['st'].append(st)
elif isinstance(st,basestring):
for s in st:
self.st(self.FMTCODE[s])
return self
def fg(self,fg):
if isinstance(fg,int):
assert (fg >= 0) and (fg < 8), 'Color should be in {0 .. 7}.'
self.prop['fg'] = 30+fg
elif isinstance(fg,basestring):
self.fg(self.COLCODE[fg])
return self
def bg(self,bg):
if isinstance(bg,int):
assert (bg >= 0) and (bg < 8), 'Color should be in {0 .. 7}.'
self.prop['bg'] = 40+bg
elif isinstance(bg,basestring):
self.bg(self.COLCODE[bg])
return self
# ------------------------------
# Format and standard output
# ------------------------------
def fmt(self,*args):
# accept multiple inputs, and concatenate them with spaces
s = " ".join(map(str,args))
# get anything that is not None
w = self.prop['st'] + [ self.prop['fg'], self.prop['bg'] ]
w = [ str(x) for x in w if x is not None ]
# return formatted string
return '\x1b[%sm%s\x1b[0m' % ( ';'.join(w), s ) if w else s
def out(self,*args):
print self.fmt(*args)
# Python 3, function
# Author: J.Hadida (jhadida87 at ggooglemail)
def cprint( fmt, fg=None, bg=None, style=None ):
"""
Colour-printer.
cprint( 'Hello!' ) # normal
cprint( 'Hello!', fg='g' ) # green
cprint( 'Hello!', fg='r', bg='w', style='bx' ) # bold red blinking on white
List of colours (for fg and bg):
k black
r red
g green
y yellow
b blue
m magenta
c cyan
w white
List of styles:
b bold
i italic
u underline
s strikethrough
x blinking
r reverse
y fast blinking
f faint
h hide
"""
COLCODE = {
'k': 0, # black
'r': 1, # red
'g': 2, # green
'y': 3, # yellow
'b': 4, # blue
'm': 5, # magenta
'c': 6, # cyan
'w': 7 # white
}
FMTCODE = {
'b': 1, # bold
'f': 2, # faint
'i': 3, # italic
'u': 4, # underline
'x': 5, # blinking
'y': 6, # fast blinking
'r': 7, # reverse
'h': 8, # hide
's': 9, # strikethrough
}
# properties
props = []
if isinstance(style,str):
props = [ FMTCODE[s] for s in style ]
if isinstance(fg,str):
props.append( 30 + COLCODE[fg] )
if isinstance(bg,str):
props.append( 40 + COLCODE[bg] )
# display
props = ';'.join([ str(x) for x in props ])
if props:
print( '\x1b[%sm%s\x1b[0m' % (props, fmt) )
else:
print( fmt )
@icom999
Copy link

icom999 commented Mar 30, 2020

Thank you for the nice console color function!

@NinjaAtWork
Copy link

Thank you for the nice console color function!
is this cross platform?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment