Created
August 25, 2017 15:08
-
-
Save Abraxos/f491670c85fd76bfeb7067cb8ea1acf7 to your computer and use it in GitHub Desktop.
Printing RGB-colored text in xterm/gnome-terminal using Python
This file contains 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
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