Skip to content

Instantly share code, notes, and snippets.

@Abraxos
Created August 25, 2017 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Abraxos/f491670c85fd76bfeb7067cb8ea1acf7 to your computer and use it in GitHub Desktop.
Save Abraxos/f491670c85fd76bfeb7067cb8ea1acf7 to your computer and use it in GitHub Desktop.
Printing RGB-colored text in xterm/gnome-terminal using Python
def color_string(str, foreground=None, background=None):
reset = '\033[0m'
if foreground:
assert len(foreground) == 3, "Foreground color needs to be a collection of 3 integer values"
R, G, B = int(foreground[0]), int(foreground[1]), int(foreground[2])
foreground = '\033[38;2;{R};{G};{B}m'.format(R=R, G=G, B=B)
else:
foreground = ''
if background:
assert len(background) == 3, "Background color needs to be a collection of 3 integer values"
R, G, B = int(background[0]), int(background[1]), int(background[2])
background = '\033[48;2;{R};{G};{B}m'.format(R=R, G=G, B=B)
else:
background = ''
return ''.join([foreground, background, str, reset])
# Print blue text on bright orange background
print(color_string('stuff', (0,0,255), (255,131,0)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment