Skip to content

Instantly share code, notes, and snippets.

@brianspiering
Created May 9, 2022 03:52
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 brianspiering/0eb64bf0faad59d3ba68795cbd246cb0 to your computer and use it in GitHub Desktop.
Save brianspiering/0eb64bf0faad59d3ba68795cbd246cb0 to your computer and use it in GitHub Desktop.
Print text to terminal in color! (The way of the future.)
#!/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.
"""
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)
print_color("Hello, World!")
print_color("[debug]", GREEN)
print_color("[warning]", YELLOW)
print_color("[error]", RED)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment