Last active
November 17, 2015 20:55
-
-
Save brianspiering/fc9daf1150281773061a to your computer and use it in GitHub Desktop.
Print text to terminal in color
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
#!/usr/bin/env python | |
""" Print text to terminal in color! | |
The way of the future. | |
""" | |
import sys | |
# Define ASCII color codes | |
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = map(lambda x: x+30, range(8)) | |
def has_colors(stream): | |
""" Check for system colors | |
This is adapted from from Python cookbook, #475186 | |
and http://blog.mathieu-leplatre.info/colored-output-in-console-with-python.html | |
""" | |
if not hasattr(stream, "isatty"): | |
return False | |
if not stream.isatty(): | |
return False # Auto color only on TTYs | |
try: | |
import curses | |
curses.setupterm() | |
return curses.tigetnum("colors") > 2 | |
except: | |
# Set to false in case of error | |
return False | |
has_colors = has_colors(sys.stdout) | |
def print_color(text, color=WHITE, newline=True): | |
""" If possible, print text message in color. | |
Define a sequences of bytes which are embedded into the text | |
which the terminal looks for and interprets as commands (not as character codes). | |
>>> print_color("Hello, World!") | |
>>> print_color("[debug]", GREEN) | |
>>> print_color("[warning]", YELLOW) | |
>>> print_color("[error]", RED) | |
""" | |
if newline: | |
newline_str = "\n" | |
else: | |
newline_str = "" | |
if has_colors: | |
seq = "\x1b[1;{color_code}m{text}\x1b[0m{newline_str}"\ | |
.format(color_code=color, | |
text=text, | |
newline_str=newline_str) | |
sys.stdout.write(seq) | |
else: | |
sys.stdout.write(text) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment