How to print colored text in Python?
How can I output colored text to the terminal in Python?
Try this simple code
def prRed(prt): print("\033[91m {}\033[00m" .format(prt)) def prGreen(prt): print("\033[92m {}\033[00m" .format(prt)) def prYellow(prt): print("\033[93m {}\033[00m" .format(prt)) def prLightPurple(prt): print("\033[94m {}\033[00m" .format(prt)) def prPurple(prt): print("\033[95m {}\033[00m" .format(prt)) def prCyan(prt): print("\033[96m {}\033[00m" .format(prt)) def prLightGray(prt): print("\033[97m {}\033[00m" .format(prt)) def prBlack(prt): print("\033[98m {}\033[00m" .format(prt)) prGreen("Hello world")
On Windows you can use module ‘win32console’ (available in some Python distributions) or module ‘ctypes’ (Python 2.5 and up) to access the Win32 API.
To see complete code that supports both ways, see the color console reporting code from Testoob.
ctypes example:
import ctypes # Constants from the Windows API STD_OUTPUT_HANDLE = -11 FOREGROUND_RED = 0x0004 # text color contains red. def get_csbi_attributes(handle): # Based on IPython's winconsole.py, written by Alexander Belchenko import struct csbi = ctypes.create_string_buffer(22) res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi) assert res (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) return wattr handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) reset = get_csbi_attributes(handle) ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED) print "Cherry on top" ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)
I have wrapped @joeld answer into a module with global functions that I can use anywhere in my code.
file: log.py
HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = "\033[1m" def disable(): HEADER = '' OKBLUE = '' OKGREEN = '' WARNING = '' FAIL = '' ENDC = '' def infog( msg): print OKGREEN + msg + ENDC def info( msg): print OKBLUE + msg + ENDC def warn( msg): print WARNING + msg + ENDC def err( msg): print FAIL + msg + ENDC
use as follows:
import log log.info("Hello World") log.err("System Error")
Stupidly simple based on @joeld’s answer
class PrintInColor: RED = '\033[91m' GREEN = '\033[92m' YELLOW = '\033[93m' LIGHT_PURPLE = '\033[94m' PURPLE = '\033[95m' END = '\033[0m' @classmethod def red(cls, s, **kwargs): print(cls.RED + s + cls.END, **kwargs) @classmethod def green(cls, s, **kwargs): print(cls.GREEN + s + cls.END, **kwargs) @classmethod def yellow(cls, s, **kwargs): print(cls.YELLOW + s + cls.END, **kwargs) @classmethod def lightPurple(cls, s, **kwargs): print(cls.LIGHT_PURPLE + s + cls.END, **kwargs) @classmethod def purple(cls, s, **kwargs): print(cls.PURPLE + s + cls.END, **kwargs)
Then just
PrintInColor.red('hello', end=' ') PrintInColor.green('world')
For Windows you cannot print to console with colors unless you’re using the win32api.
For Linux it’s as simple as using print, with the escape sequences outlined here:
For the character to print like a box, it really depends on what font you are using for the console window. The pound symbol works well, but it depends on the font:
#
# Pure Python 3.x demo, 256 colors # Works with bash under Linux and MacOS fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m" bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m" def print_six(row, format, end="\n"): for col in range(6): color = row*6 + col - 2 if color>=0: text = "{:3d}".format(color) print (format(text,color), end=" ") else: print(end=" ") # four spaces print(end=end) for row in range(0, 43): print_six(row, fg, " ") print_six(row, bg) # Simple usage: print(fg("text", 160))
def black(text): print('\033[30m', text, '\033[0m', sep='') def red(text): print('\033[31m', text, '\033[0m', sep='') def green(text): print('\033[32m', text, '\033[0m', sep='') def yellow(text): print('\033[33m', text, '\033[0m', sep='') def blue(text): print('\033[34m', text, '\033[0m', sep='') def magenta(text): print('\033[35m', text, '\033[0m', sep='') def cyan(text): print('\033[36m', text, '\033[0m', sep='') def gray(text): print('\033[90m', text, '\033[0m', sep='') black("BLACK") red("RED") green("GREEN") yellow("YELLOW") blue("BLACK") magenta("MAGENTA") cyan("CYAN") gray("GRAY")
I ended up doing this, I felt it was cleanest:
formatters = { 'RED': '\033[91m', 'GREEN': '\033[92m', 'END': '\033[0m', } print 'Master is currently {RED}red{END}!'.format(**formatters) print 'Help make master {GREEN}green{END} again!'.format(**formatters)
Building on @joeld answer, using https://pypi.python.org/pypi/lazyme pip install -U lazyme
:
from lazyme.string import color_print >>> color_print('abc') abc >>> color_print('abc', color='pink') abc >>> color_print('abc', color='red') abc >>> color_print('abc', color='yellow') abc >>> color_print('abc', color='green') abc >>> color_print('abc', color='blue', underline=True) abc >>> color_print('abc', color='blue', underline=True, bold=True) abc >>> color_print('abc', color='pink', underline=True, bold=True) abc
Screenshot:
Some updates to the color_print
with new formatters, e.g.:
>>> from lazyme.string import palette, highlighter, formatter >>> from lazyme.string import color_print >>> palette.keys() # Available colors. ['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red'] >>> highlighter.keys() # Available highlights. ['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red'] >>> formatter.keys() # Available formatter, ['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']
Note: italic
, fast blinking
and strikethrough
may not work on all terminals, doesn’t work on Mac / Ubuntu.
E.g.
>>> color_print('foo bar', color='pink', highlight='white') foo bar >>> color_print('foo bar', color='pink', highlight='white', reverse=True) foo bar >>> color_print('foo bar', color='pink', highlight='white', bold=True) foo bar >>> color_print('foo bar', color='pink', highlight='white', faint=True) foo bar >>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True) foo bar >>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True) foo bar
Screenshot:
note how well the with
keyword mixes with modifiers like these that need to be reset (using Python 3 and Colorama):
from colorama import Fore, Style import sys class Highlight: def __init__(self, clazz, color): self.color = color self.clazz = clazz def __enter__(self): print(self.color, end="") def __exit__(self, type, value, traceback): if self.clazz == Fore: print(Fore.RESET, end="") else: assert self.clazz == Style print(Style.RESET_ALL, end="") sys.stdout.flush() with Highlight(Fore, Fore.GREEN): print("this is highlighted") print("this is not")