[python] How to print colored text to the terminal?

How can I output colored text to the terminal in Python?

This question is related to python terminal output ansi-colors

The answer is


You could use Clint:

from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')

You want to learn about ANSI escape sequences. Here's a brief example:

CSI = "\x1B["
print(CSI+"31;40m" + "Colored Text" + CSI + "0m")

For more information, see ANSI escape code.

For a block character, try a Unicode character like \u2588:

print(u"\u2588")

Putting it all together:

print(CSI+"31;40m" + u"\u2588" + CSI + "0m")

If you are using Windows, then here you go!

# Display text on a Windows console
# Windows XP with Python 2.7 or Python 3.2
from ctypes import windll

# Needed for Python2/Python3 diff
try:
    input = raw_input
except:
    pass
STD_OUTPUT_HANDLE = -11
stdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
# Look at the output and select the color you want.
# For instance, hex E is yellow on black.
# Hex 1E is yellow on blue.
# Hex 2E is yellow on green and so on.
for color in range(0, 75):
     windll.kernel32.SetConsoleTextAttribute(stdout_handle, color)
     print("%X --> %s" % (color, "Have a fine day!"))
     input("Press Enter to go on ... ")

To address this problem I created a mind-numbingly simple package to print strings with interpolated color codes, called icolor.

icolor includes two functions: cformat and cprint, each of which takes a string with substrings that are interpolated to map to ANSI escape sequences e.g.

from icolor import cformat # there is also cprint

cformat("This is #RED;a red string, partially with a #xBLUE;blue background")
'This is \x1b[31ma red string, partially with a \x1b[44mblue background\x1b[0m'

All the ANSI colors are included (e.g. #RED;, #BLUE;, etc.), as well as #RESET;, #BOLD; and others.

Background colors have an x prefix, so a green background would be #xGREEN;.

One can escape # with ##.

Given its simplicity, the best documentation is probably the code itself.

It is on PYPI, so one can sudo easy_install icolor.


Building on joeld's 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:

Enter image description here


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, and they don't work on Mac and 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:

Enter image description here


Some of the solutions like:

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)

print(fg("text", 160))

OR

def colored(r, g, b, text):
    return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)


text = 'Hello, World!'
colored_text = colored(255, 0, 0, text)
print(colored_text)

OR

class Color:
    COLOR = [f"\33[{i}m" for i in range(44)]

for i in range(44):
    print(Color.COLOR[i] + 'text')

might not work on Windows 10 terminals or PowerShell windows or their might be other cases where these might not work directly.

But on inserting, these two small lines at the beginning of the program might help:

import os
os.system('')

os.system('') allows you to print ANSI codes in the Terminal which colors your output according to your choice (but there can be other system specific functions that you might need to call, to be able to print colored text in terminal).


You can use the Python implementation of the curses library: curses — Terminal handling for character-cell displays

Also, run this and you'll find your box:

for i in range(255):
    print i, chr(i)

I ended up doing this, and 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)

This is, in my opinion, the easiest method. As long as you have the RGB values of the color you want, this should work:

def colored(r, g, b, text):
    return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)

An example of printing red text:

text = 'Hello, World!'
colored_text = colored(255, 0, 0, text)
print(colored_text)

#or

print(colored(255, 0, 0, 'Hello, World! '))

Multi-colored text

text = colored(255, 0, 0, 'Hello, ') + colored(0, 255, 0, 'World')
print(text)

If you are programming a game perhaps you would like to change the background color and use only spaces? For example:

print " "+ "\033[01;41m" + " " +"\033[01;46m"  + "  " + "\033[01;42m"

For the characters

Your terminal most probably uses Unicode (typically UTF-8 encoded) characters, so it's only a matter of the appropriate font selection to see your favorite character. Unicode char U+2588, "Full block" is the one I would suggest you use.

Try the following:

import unicodedata
fp= open("character_list", "w")
for index in xrange(65536):
    char= unichr(index)
    try: its_name= unicodedata.name(char)
    except ValueError: its_name= "N/A"
    fp.write("%05d %04x %s %s\n" % (index, index, char.encode("UTF-8"), its_name)
fp.close()

Examine the file later with your favourite viewer.

For the colors

curses is the module you want to use. Check this tutorial.


I wrote a simple module, available at: http://pypi.python.org/pypi/colorconsole

It works with Windows, Mac OS X and Linux. It uses ANSI for Linux and Mac, but native calls to console functions on Windows. You have colors, cursor positioning and keyboard input. It is not a replacement for curses, but can be very useful if you need to use in simple scripts or ASCII games.


I am new to Python and I'm excited every time I discover topics, like this one. But this time (suddenly) I feel like I have what to say. Especially because a few minutes ago I discovered a wow thing in Python (at least for me now):

Context Managers

from contextlib import contextmanager
# FORECOLOR
BLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'
# BACKGOUND
BLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'

@contextmanager
def printESC(prefix, color, text):
  print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')
  yield
  print("{prefix}0m".format(prefix=prefix))

with printESC('\x1B[', REDFC, 'Colored Text'):
  pass

Example

Or just like this:

# FORECOLOR
BLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'
# BACKGOUND
BLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'

def printESC(prefix, color, text):
  print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')
  print("{prefix}0m".format(prefix=prefix))

printESC('\x1B[', REDFC, 'Colored Text')

This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some Python code from the Blender build scripts:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

To use code like this, you can do something like:

print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)

Or, with Python 3.6+:

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

This will work on unixes including OS X, Linux and Windows (provided you use ANSICON, or in Windows 10 provided you enable VT100 emulation). There are ANSI codes for setting the color, moving the cursor, and more.

If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "curses" module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO is a good introduction.

If you are not using extended ASCII (i.e., not on a PC), you are stuck with the ASCII characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM extended ASCII character set, you have many more options. Characters 176, 177, 178 and 219 are the "block characters".

Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the Dwarf Fortress Wiki see (user-made tilesets).

The Text Mode Demo Contest has more resources for doing graphics in text mode.


To address this problem I created a mind-numbingly simple package to print strings with interpolated color codes, called icolor.

icolor includes two functions: cformat and cprint, each of which takes a string with substrings that are interpolated to map to ANSI escape sequences e.g.

from icolor import cformat # there is also cprint

cformat("This is #RED;a red string, partially with a #xBLUE;blue background")
'This is \x1b[31ma red string, partially with a \x1b[44mblue background\x1b[0m'

All the ANSI colors are included (e.g. #RED;, #BLUE;, etc.), as well as #RESET;, #BOLD; and others.

Background colors have an x prefix, so a green background would be #xGREEN;.

One can escape # with ##.

Given its simplicity, the best documentation is probably the code itself.

It is on PYPI, so one can sudo easy_install icolor.


An easier option would be to use the cprint function from the termcolor package.

color-print-python

It also supports %s, %d format of printing:

Enter image description here


You want to learn about ANSI escape sequences. Here's a brief example:

CSI = "\x1B["
print(CSI+"31;40m" + "Colored Text" + CSI + "0m")

For more information, see ANSI escape code.

For a block character, try a Unicode character like \u2588:

print(u"\u2588")

Putting it all together:

print(CSI+"31;40m" + u"\u2588" + CSI + "0m")

For the characters

Your terminal most probably uses Unicode (typically UTF-8 encoded) characters, so it's only a matter of the appropriate font selection to see your favorite character. Unicode char U+2588, "Full block" is the one I would suggest you use.

Try the following:

import unicodedata
fp= open("character_list", "w")
for index in xrange(65536):
    char= unichr(index)
    try: its_name= unicodedata.name(char)
    except ValueError: its_name= "N/A"
    fp.write("%05d %04x %s %s\n" % (index, index, char.encode("UTF-8"), its_name)
fp.close()

Examine the file later with your favourite viewer.

For the colors

curses is the module you want to use. Check this tutorial.


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!")

I wrote a module that handles colors in Linux, OS X, and Windows. It supports all 16 colors on all platforms, you can set foreground and background colors at different times, and the string objects give sane results for things like len() and .capitalize().

https://github.com/Robpol86/colorclass

Example on Windows cmd.exe


The answer is Colorama for all cross-platform coloring in Python.

It supports Python 3.5+ as well as Python 2.7.

And as of January 2021 it is maintained.

Example screenshot: example screenshot


asciimatics provides a portable support for building text UI and animations:

#!/usr/bin/env python
from asciimatics.effects import RandomNoise  # $ pip install asciimatics
from asciimatics.renderers import SpeechBubble, Rainbow
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.exceptions import ResizeScreenError


def demo(screen):
    render = Rainbow(screen, SpeechBubble('Rainbow'))
    effects = [RandomNoise(screen, signal=render)]
    screen.play([Scene(effects, -1)], stop_on_resize=True)

while True:
    try:
        Screen.wrapper(demo)
        break
    except ResizeScreenError:
        pass

Asciicast:

rainbow-colored text among ascii noise


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")

Try online


For Windows you cannot print to console with colors unless you're using the Win32 API.

For Linux it's as simple as using print, with the escape sequences outlined here:

Colors

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:

#

print("\033[1;32;40m Bright Green  \n")

1


An easier option would be to use the cprint function from the termcolor package.

color-print-python

It also supports %s, %d format of printing:

Enter image description here


For Windows you cannot print to console with colors unless you're using the Win32 API.

For Linux it's as simple as using print, with the escape sequences outlined here:

Colors

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:

#

I generated a class with all the colors using a for loop to iterate every combination of color up to 100, and then wrote a class with Python colors. Copy and paste as you will, GPLv2 by me:

class colors:
    '''Colors class:
    Reset all colors with colors.reset
    Two subclasses fg for foreground and bg for background.
    Use as colors.subclass.colorname.
    i.e. colors.fg.red or colors.bg.green
    Also, the generic bold, disable, underline, reverse, strikethrough,
    and invisible work with the main class
    i.e. colors.bold
    '''
    reset='\033[0m'
    bold='\033[01m'
    disable='\033[02m'
    underline='\033[04m'
    reverse='\033[07m'
    strikethrough='\033[09m'
    invisible='\033[08m'
    class fg:
        black='\033[30m'
        red='\033[31m'
        green='\033[32m'
        orange='\033[33m'
        blue='\033[34m'
        purple='\033[35m'
        cyan='\033[36m'
        lightgrey='\033[37m'
        darkgrey='\033[90m'
        lightred='\033[91m'
        lightgreen='\033[92m'
        yellow='\033[93m'
        lightblue='\033[94m'
        pink='\033[95m'
        lightcyan='\033[96m'
    class bg:
        black='\033[40m'
        red='\033[41m'
        green='\033[42m'
        orange='\033[43m'
        blue='\033[44m'
        purple='\033[45m'
        cyan='\033[46m'
        lightgrey='\033[47m'

You can use the Python implementation of the curses library: curses — Terminal handling for character-cell displays

Also, run this and you'll find your box:

for i in range(255):
    print i, chr(i)

For the characters

Your terminal most probably uses Unicode (typically UTF-8 encoded) characters, so it's only a matter of the appropriate font selection to see your favorite character. Unicode char U+2588, "Full block" is the one I would suggest you use.

Try the following:

import unicodedata
fp= open("character_list", "w")
for index in xrange(65536):
    char= unichr(index)
    try: its_name= unicodedata.name(char)
    except ValueError: its_name= "N/A"
    fp.write("%05d %04x %s %s\n" % (index, index, char.encode("UTF-8"), its_name)
fp.close()

Examine the file later with your favourite viewer.

For the colors

curses is the module you want to use. Check this tutorial.


asciimatics provides a portable support for building text UI and animations:

#!/usr/bin/env python
from asciimatics.effects import RandomNoise  # $ pip install asciimatics
from asciimatics.renderers import SpeechBubble, Rainbow
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.exceptions import ResizeScreenError


def demo(screen):
    render = Rainbow(screen, SpeechBubble('Rainbow'))
    effects = [RandomNoise(screen, signal=render)]
    screen.play([Scene(effects, -1)], stop_on_resize=True)

while True:
    try:
        Screen.wrapper(demo)
        break
    except ResizeScreenError:
        pass

Asciicast:

rainbow-colored text among ascii noise


I suggest this new library Printy. They just released version 1.2.0 as a cross-platform library.

Check it out: Printy on GitHub

It is based on flags so you can do stuff like

from printy import printy

# With global flags, this will apply a bold (B) red (r) color and an underline (U) to the whole text
printy("Hello, World!", "rBU")

# With inline formats, this will apply a dim (D)
#blue (b) to the word 'Hello' and a stroken (S)
#yellow (y) to the word 'world', and the rest will remain as the predefined format
printy("this is a [bD]Hello@ [yS]world@ text")

Enter image description here


Use pyfancy. It is a simple way to do color in the terminal!

Example:

print(pyfancy.RED + "Hello Red" + pyfancy.END)

Emoji

You can use colors for text as others mentioned in their answers to have colorful text with a background or foreground color.

But you can use emojis instead! for example, you can use?? for warning messages and for error messages.

Or simply use these notebooks as a color:

: error message
: warning message
: ok status message
: action message
: canceled status message
: Or anything you like and want to recognize immediately by color

Bonus:

This method also helps you to quickly scan and find logs directly in the source code.

But some operating systems (including some Linux distributions in some version with some window managers) default emoji font is not colorful by default and you may want to make them colorful, first.


There is also the Python termcolor module. Usage is pretty simple:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

Or in Python 3:

print(colored('hello', 'red'), colored('world', 'green'))

It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...


If you are using Django:

>>> from django.utils.termcolors import colorize
>>> print colorize("Hello, World!", fg="blue", bg='red',
...                 opts=('bold', 'blink', 'underscore',))
Hello World!
>>> help(colorize)

Snapshot:

Image

(I generally use colored output for debugging on runserver terminal, so I added it.)

You can test if it is installed in your machine: $ python -c "import django; print django.VERSION". To install it, check: How to install Django

Give it a try!!


Print a string that starts a color/style, then the string, and then end the color/style change with '\x1b[0m':

print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')

Success with green background example

Get a table of format options for shell text with the following code:

def print_format_table():
    """
    prints table of formatted text format options
    """
    for style in range(8):
        for fg in range(30,38):
            s1 = ''
            for bg in range(40,48):
                format = ';'.join([str(style), str(fg), str(bg)])
                s1 += '\x1b[%sm %s \x1b[0m' % (format, format)
            print(s1)
        print('\n')

print_format_table()

Light-on-dark example (complete)

Enter image description here

Dark-on-light example (partial)

Top part of output


There is also the Python termcolor module. Usage is pretty simple:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

Or in Python 3:

print(colored('hello', 'red'), colored('world', 'green'))

It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...


The answer is Colorama for all cross-platform coloring in Python.

It supports Python 3.5+ as well as Python 2.7.

And as of January 2021 it is maintained.

Example screenshot: example screenshot


https://raw.github.com/fabric/fabric/master/fabric/colors.py

"""
.. versionadded:: 0.9.2

Functions for wrapping strings in ANSI color codes.

Each function within this module returns the input string ``text``, wrapped
with ANSI color codes for the appropriate color.

For example, to print some text as green on supporting terminals::

    from fabric.colors import green

    print(green("This text is green!"))

Because these functions simply return modified strings, you can nest them::

    from fabric.colors import red, green

    print(red("This sentence is red, except for " + \
          green("these words, which are green") + "."))

If ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on
for that particular invocation, which usually shows up as a bold or brighter
version of the original color on most terminals.
"""


def _wrap_with(code):

    def inner(text, bold=False):
        c = code
        if bold:
            c = "1;%s" % c
        return "\033[%sm%s\033[0m" % (c, text)
    return inner

red = _wrap_with('31')
green = _wrap_with('32')
yellow = _wrap_with('33')
blue = _wrap_with('34')
magenta = _wrap_with('35')
cyan = _wrap_with('36')
white = _wrap_with('37')

sty is similar to colorama, but it's less verbose, supports 8-bit and 24-bit (RGB) colors, supports all effects (bold, underline, etc.) allows you to register your own styles, is fully typed, supports muting, is really flexible, well documented and more...

Examples:

from sty import fg, bg, ef, rs

foo = fg.red + 'This is red text!' + fg.rs
bar = bg.blue + 'This has a blue background!' + bg.rs
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs

# Add custom colors:

from sty import Style, RgbFg

fg.orange = Style(RgbFg(255, 150, 50))

buf = fg.orange + 'Yay, Im orange.' + fg.rs

print(foo, bar, baz, qux, qui, buf, sep='\n')

prints:

Enter image description here

Demo:

Enter image description here


import click

click.secho('Hello, World!', fg='green')
click.secho('Some more text', bg='blue', fg='white')
click.secho('ATTENTION', blink=True, bold=True)

click (CLI library) has a very convenient way of doing this, and is worth considering if you're writing a command-line tool, anyway.


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")

I have wrapped joeld's answer into a module with global functions that I can use anywhere in my code.

File: log.py

def enable():
    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)

enable()

Use as follows:

import log
log.info("Hello, World!")
log.err("System Error")

For Windows you cannot print to console with colors unless you're using the Win32 API.

For Linux it's as simple as using print, with the escape sequences outlined here:

Colors

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:

#

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 wrote a simple module, available at: http://pypi.python.org/pypi/colorconsole

It works with Windows, Mac OS X and Linux. It uses ANSI for Linux and Mac, but native calls to console functions on Windows. You have colors, cursor positioning and keyboard input. It is not a replacement for curses, but can be very useful if you need to use in simple scripts or ASCII games.


I created a project (console-color) and already published it to PyPI.

You can throw pip install console-color to install it.

And I write the document with Sphinx-read-the-doc, see here.

You can get more example from google-colab.

I still post some example to attract the user to click the above link:

# cprint is something like below
# cprint(text: str, fore: T_RGB = None, bg: T_RGB = None, style: Style = '')
# where T_RGB = Union[Tuple[int, int, int], str] for example. You can input (255, 0, 0) or '#ff0000' or 'ff0000'. They are OK.
# The Style you can input the ``Style.`` (the IDE will help you to choose what you wanted)

# from console_color import RGB, Fore, Style, cprint, create_print
from console_color import *

cprint("Hello, World!", RGB.RED, RGB.YELLOW, Style.BOLD+Style.URL+Style.STRIKE)
cprint("Hello, World!", fore=(255, 0, 0), bg="ffff00", style=Style.BOLD+Style.URL+Style.STRIKE)

Enter image description here

Of course, you don’t have to enter all the parameters. You can just add the attributes you want.


To be honest, this project is not special. It just uses the f"\033[{target};2;{r};{g};{b}m{text}{style}" where target is 38 or 48, text is your input string, and style is '\33[0m', '\33[1m' ... '\033[9m'. Some kind of stuff.

And I just make it easy to use (at least for me).


Yet another PyPI module that wraps the Python 3 print function:

https://pypi.python.org/pypi/colorprint

It's usable in Python 2.x if you also from __future__ import print. Here is a Python 2 example from the modules PyPI page:

from __future__ import print_function
from colorprint import *

print('Hello', 'world', color='blue', end='', sep=', ')
print('!', color='red', format=['bold', 'blink'])

It outputs "Hello, world!" with the words in blue and the exclamation mark bold red and blinking.


I generated a class with all the colors using a for loop to iterate every combination of color up to 100, and then wrote a class with Python colors. Copy and paste as you will, GPLv2 by me:

class colors:
    '''Colors class:
    Reset all colors with colors.reset
    Two subclasses fg for foreground and bg for background.
    Use as colors.subclass.colorname.
    i.e. colors.fg.red or colors.bg.green
    Also, the generic bold, disable, underline, reverse, strikethrough,
    and invisible work with the main class
    i.e. colors.bold
    '''
    reset='\033[0m'
    bold='\033[01m'
    disable='\033[02m'
    underline='\033[04m'
    reverse='\033[07m'
    strikethrough='\033[09m'
    invisible='\033[08m'
    class fg:
        black='\033[30m'
        red='\033[31m'
        green='\033[32m'
        orange='\033[33m'
        blue='\033[34m'
        purple='\033[35m'
        cyan='\033[36m'
        lightgrey='\033[37m'
        darkgrey='\033[90m'
        lightred='\033[91m'
        lightgreen='\033[92m'
        yellow='\033[93m'
        lightblue='\033[94m'
        pink='\033[95m'
        lightcyan='\033[96m'
    class bg:
        black='\033[40m'
        red='\033[41m'
        green='\033[42m'
        orange='\033[43m'
        blue='\033[44m'
        purple='\033[45m'
        cyan='\033[46m'
        lightgrey='\033[47m'

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)

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")

Try online


You want to learn about ANSI escape sequences. Here's a brief example:

CSI = "\x1B["
print(CSI+"31;40m" + "Colored Text" + CSI + "0m")

For more information, see ANSI escape code.

For a block character, try a Unicode character like \u2588:

print(u"\u2588")

Putting it all together:

print(CSI+"31;40m" + u"\u2588" + CSI + "0m")

If you are using Django:

>>> from django.utils.termcolors import colorize
>>> print colorize("Hello, World!", fg="blue", bg='red',
...                 opts=('bold', 'blink', 'underscore',))
Hello World!
>>> help(colorize)

Snapshot:

Image

(I generally use colored output for debugging on runserver terminal, so I added it.)

You can test if it is installed in your machine: $ python -c "import django; print django.VERSION". To install it, check: How to install Django

Give it a try!!


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')

My two cents (PyColorTerm):

Installation:

sudo apt-get install python-pip
pip install pycolorterm

Python script:

from pycolorterm import pycolorterm

with pycolorterm.pretty_output(pycolorterm.FG_GREEN) as out:
    out.write('Works OK!')

"works OK!" shows in green.


Rich is a relatively new Python library for working with color in the terminal.

There are a few ways of working with color in Rich. The quickest way to get started would be the rich print method which renders a BBCode-like syntax in to ANSI control codes:

from rich import print
print("[red]Color[/] in the [bold magenta]Terminal[/]!")

There are other ways of applying color with Rich (regex, syntax) and related formatting features.

Screenshot of Rich


I have a library called colorit. It is super simple.

Here are some examples:

from colorit import *

# Use this to ensure that ColorIt will be usable by certain command line interfaces
# Note: This clears the terminal
init_colorit()

# Foreground
print(color("This text is red", Colors.red))
print(color("This text is orange", Colors.orange))
print(color("This text is yellow", Colors.yellow))
print(color("This text is green", Colors.green))
print(color("This text is blue", Colors.blue))
print(color("This text is purple", Colors.purple))
print(color("This text is white", Colors.white))

# Background
print(background("This text has a background that is red", Colors.red))
print(background("This text has a background that is orange", Colors.orange))
print(background("This text has a background that is yellow", Colors.yellow))
print(background("This text has a background that is green", Colors.green))
print(background("This text has a background that is blue", Colors.blue))
print(background("This text has a background that is purple", Colors.purple))
print(background("This text has a background that is white", Colors.white))

# Custom
print(color("This color has a custom grey text color", (150, 150, 150)))
print(background("This color has a custom grey background", (150, 150, 150)))

# Combination
print(
    background(
        color("This text is blue with a white background", Colors.blue), Colors.white
    )
)

# If you are using Windows Command Line, this is so that it doesn't close immediately
input()

This gives you:

Picture of ColorIt

It's also worth noting that this is cross platform and has been tested on Mac, Linux, and Windows.

You might want to try it out: https://github.com/SuperMaZingCoder/colorit

colorit is now available to be installed with PyPi! You can install it with pip install color-it on Windows and pip3 install color-it on macOS and Linux.


If you are programming a game perhaps you would like to change the background color and use only spaces? For example:

print " "+ "\033[01;41m" + " " +"\033[01;46m"  + "  " + "\033[01;42m"

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)

Yet another PyPI module that wraps the Python 3 print function:

https://pypi.python.org/pypi/colorprint

It's usable in Python 2.x if you also from __future__ import print. Here is a Python 2 example from the modules PyPI page:

from __future__ import print_function
from colorprint import *

print('Hello', 'world', color='blue', end='', sep=', ')
print('!', color='red', format=['bold', 'blink'])

It outputs "Hello, world!" with the words in blue and the exclamation mark bold red and blinking.


https://raw.github.com/fabric/fabric/master/fabric/colors.py

"""
.. versionadded:: 0.9.2

Functions for wrapping strings in ANSI color codes.

Each function within this module returns the input string ``text``, wrapped
with ANSI color codes for the appropriate color.

For example, to print some text as green on supporting terminals::

    from fabric.colors import green

    print(green("This text is green!"))

Because these functions simply return modified strings, you can nest them::

    from fabric.colors import red, green

    print(red("This sentence is red, except for " + \
          green("these words, which are green") + "."))

If ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on
for that particular invocation, which usually shows up as a bold or brighter
version of the original color on most terminals.
"""


def _wrap_with(code):

    def inner(text, bold=False):
        c = code
        if bold:
            c = "1;%s" % c
        return "\033[%sm%s\033[0m" % (c, text)
    return inner

red = _wrap_with('31')
green = _wrap_with('32')
yellow = _wrap_with('33')
blue = _wrap_with('34')
magenta = _wrap_with('35')
cyan = _wrap_with('36')
white = _wrap_with('37')

The simplest way I can find is not to use ANSI escape codes, but use Fore from import module colorama. Take a look at the code below:

from colorama import Fore, Style

print(Fore.MAGENTA + "IZZ MAGENTA BRUH.")

print(Style.RESET_ALL + "IZZ BACK TO NORMALZ.")

compared to the ANSI escape code:

print("\u001b[31m IZZ RED (NO MAGENTA ON ANSI CODES).\u001b[0m")

print("BACK TO NORMALZ.")

Here is a simple function I use to print a text message in color without having to remember ANSI codes but rather using standard RGB tuples to define the foreground and background colors.

def print_in_color(txt_msg, fore_tuple, back_tuple, ):
    # Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple
    # text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)
    rf,bf,gf = fore_tuple
    rb,gb,bb = back_tuple
    msg = '{0}' + txt_msg
    mat = '\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'
    print(msg .format(mat))
    print('\33[0m') # Returns default print color to back to black

# Example of use using a message with variables
fore_color = 'cyan'
back_color = 'dark green'
msg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
print_in_color(msg, (0,255,255), (0,127,127))

I have a library called colorit. It is super simple.

Here are some examples:

from colorit import *

# Use this to ensure that ColorIt will be usable by certain command line interfaces
# Note: This clears the terminal
init_colorit()

# Foreground
print(color("This text is red", Colors.red))
print(color("This text is orange", Colors.orange))
print(color("This text is yellow", Colors.yellow))
print(color("This text is green", Colors.green))
print(color("This text is blue", Colors.blue))
print(color("This text is purple", Colors.purple))
print(color("This text is white", Colors.white))

# Background
print(background("This text has a background that is red", Colors.red))
print(background("This text has a background that is orange", Colors.orange))
print(background("This text has a background that is yellow", Colors.yellow))
print(background("This text has a background that is green", Colors.green))
print(background("This text has a background that is blue", Colors.blue))
print(background("This text has a background that is purple", Colors.purple))
print(background("This text has a background that is white", Colors.white))

# Custom
print(color("This color has a custom grey text color", (150, 150, 150)))
print(background("This color has a custom grey background", (150, 150, 150)))

# Combination
print(
    background(
        color("This text is blue with a white background", Colors.blue), Colors.white
    )
)

# If you are using Windows Command Line, this is so that it doesn't close immediately
input()

This gives you:

Picture of ColorIt

It's also worth noting that this is cross platform and has been tested on Mac, Linux, and Windows.

You might want to try it out: https://github.com/SuperMaZingCoder/colorit

colorit is now available to be installed with PyPi! You can install it with pip install color-it on Windows and pip3 install color-it on macOS and Linux.


My favorite way is with the Blessings library (full disclosure: I wrote it). For example:

from blessings import Terminal

t = Terminal()
print t.red('This is red.')
print t.bold_bright_red_on_black('Bright red on black')

To print colored bricks, the most reliable way is to print spaces with background colors. I use this technique to draw the progress bar in nose-progressive:

print t.on_green(' ')

You can print in specific locations as well:

with t.location(0, 5):
    print t.on_yellow(' ')

If you have to muck with other terminal capabilities in the course of your game, you can do that as well. You can use Python's standard string formatting to keep it readable:

print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)

The nice thing about Blessings is that it does its best to work on all sorts of terminals, not just the (overwhelmingly common) ANSI-color ones. It also keeps unreadable escape sequences out of your code while remaining concise to use. Have fun!


There is also the Python termcolor module. Usage is pretty simple:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

Or in Python 3:

print(colored('hello', 'red'), colored('world', 'green'))

It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...


You can use shell escape characters that are available from any language. These escape characters start with the ESC character followed by a number of arguments.

For example, to output a red "Hello, World!" string in your terminal:

echo "\e[31m Hello, World! \e[0m"

Or from a Python script:

print("\e[31m Hello world \e[0m")

Also, I wrote an article about Escape sequences that can probably help you get a better grasp of this mechanism.


Here's a solution that works on Windows 10 natively.

Using a system call, such as os.system(""), allows colours to be printed in Command Prompt and Powershell natively:

import os

# System call
os.system("")

# Class of different styles
class style():
    BLACK = '\033[30m'
    RED = '\033[31m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'
    MAGENTA = '\033[35m'
    CYAN = '\033[36m'
    WHITE = '\033[37m'
    UNDERLINE = '\033[4m'
    RESET = '\033[0m'

print(style.YELLOW + "Hello, World!")

Note: Windows does not fully support ANSI codes, whether through system calls or modules. Not all text decoration is supported, and although the bright colours display, they are identical to the regular colours.

Thanks to @j-l for finding an even shorter method.

tl;dr: Add os.system("")


Define a string that starts a color and a string that ends the color. Then print your text with the start string at the front and the end string at the end.

CRED = '\033[91m'
CEND = '\033[0m'
print(CRED + "Error, does not compute!" + CEND)

This produces the following in Bash, in urxvt with a Zenburn-style color scheme:

Output colors

Through experimentation, we can get more colors:

Color matrix

Note: \33[5m and \33[6m are blinking.

This way we can create a full color collection:

CEND      = '\33[0m'
CBOLD     = '\33[1m'
CITALIC   = '\33[3m'
CURL      = '\33[4m'
CBLINK    = '\33[5m'
CBLINK2   = '\33[6m'
CSELECTED = '\33[7m'

CBLACK  = '\33[30m'
CRED    = '\33[31m'
CGREEN  = '\33[32m'
CYELLOW = '\33[33m'
CBLUE   = '\33[34m'
CVIOLET = '\33[35m'
CBEIGE  = '\33[36m'
CWHITE  = '\33[37m'

CBLACKBG  = '\33[40m'
CREDBG    = '\33[41m'
CGREENBG  = '\33[42m'
CYELLOWBG = '\33[43m'
CBLUEBG   = '\33[44m'
CVIOLETBG = '\33[45m'
CBEIGEBG  = '\33[46m'
CWHITEBG  = '\33[47m'

CGREY    = '\33[90m'
CRED2    = '\33[91m'
CGREEN2  = '\33[92m'
CYELLOW2 = '\33[93m'
CBLUE2   = '\33[94m'
CVIOLET2 = '\33[95m'
CBEIGE2  = '\33[96m'
CWHITE2  = '\33[97m'

CGREYBG    = '\33[100m'
CREDBG2    = '\33[101m'
CGREENBG2  = '\33[102m'
CYELLOWBG2 = '\33[103m'
CBLUEBG2   = '\33[104m'
CVIOLETBG2 = '\33[105m'
CBEIGEBG2  = '\33[106m'
CWHITEBG2  = '\33[107m'

Here is the code to generate the test:

x = 0
for i in range(24):
  colors = ""
  for j in range(5):
    code = str(x+j)
    colors = colors + "\33[" + code + "m\\33[" + code + "m\033[0m "
  print(colors)
  x = x + 5

If you are programming a game perhaps you would like to change the background color and use only spaces? For example:

print " "+ "\033[01;41m" + " " +"\033[01;46m"  + "  " + "\033[01;42m"

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)

You can use shell escape characters that are available from any language. These escape characters start with the ESC character followed by a number of arguments.

For example, to output a red "Hello, World!" string in your terminal:

echo "\e[31m Hello, World! \e[0m"

Or from a Python script:

print("\e[31m Hello world \e[0m")

Also, I wrote an article about Escape sequences that can probably help you get a better grasp of this mechanism.


Rich is a relatively new Python library for working with color in the terminal.

There are a few ways of working with color in Rich. The quickest way to get started would be the rich print method which renders a BBCode-like syntax in to ANSI control codes:

from rich import print
print("[red]Color[/] in the [bold magenta]Terminal[/]!")

There are other ways of applying color with Rich (regex, syntax) and related formatting features.

Screenshot of Rich


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")

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')

My two cents (PyColorTerm):

Installation:

sudo apt-get install python-pip
pip install pycolorterm

Python script:

from pycolorterm import pycolorterm

with pycolorterm.pretty_output(pycolorterm.FG_GREEN) as out:
    out.write('Works OK!')

"works OK!" shows in green.


For Windows you cannot print to console with colors unless you're using the Win32 API.

For Linux it's as simple as using print, with the escape sequences outlined here:

Colors

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:

#

Print a string that starts a color/style, then the string, and then end the color/style change with '\x1b[0m':

print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')

Success with green background example

Get a table of format options for shell text with the following code:

def print_format_table():
    """
    prints table of formatted text format options
    """
    for style in range(8):
        for fg in range(30,38):
            s1 = ''
            for bg in range(40,48):
                format = ';'.join([str(style), str(fg), str(bg)])
                s1 += '\x1b[%sm %s \x1b[0m' % (format, format)
            print(s1)
        print('\n')

print_format_table()

Light-on-dark example (complete)

Enter image description here

Dark-on-light example (partial)

Top part of output


Use pyfancy. It is a simple way to do color in the terminal!

Example:

print(pyfancy.RED + "Hello Red" + pyfancy.END)

Here's a curses example:

import curses

def main(stdscr):
    stdscr.clear()
    if curses.has_colors():
        for i in xrange(1, curses.COLORS):
            curses.init_pair(i, i, curses.COLOR_BLACK)
            stdscr.addstr("COLOR %d! " % i, curses.color_pair(i))
            stdscr.addstr("BOLD! ", curses.color_pair(i) | curses.A_BOLD)
            stdscr.addstr("STANDOUT! ", curses.color_pair(i) | curses.A_STANDOUT)
            stdscr.addstr("UNDERLINE! ", curses.color_pair(i) | curses.A_UNDERLINE)
            stdscr.addstr("BLINK! ", curses.color_pair(i) | curses.A_BLINK)
            stdscr.addstr("DIM! ", curses.color_pair(i) | curses.A_DIM)
            stdscr.addstr("REVERSE! ", curses.color_pair(i) | curses.A_REVERSE)
    stdscr.refresh()
    stdscr.getch()

if __name__ == '__main__':
    print "init..."
    curses.wrapper(main)

import click

click.secho('Hello, World!', fg='green')
click.secho('Some more text', bg='blue', fg='white')
click.secho('ATTENTION', blink=True, bold=True)

click (CLI library) has a very convenient way of doing this, and is worth considering if you're writing a command-line tool, anyway.


Building on joeld's 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:

Enter image description here


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, and they don't work on Mac and 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:

Enter image description here


I have wrapped joeld's answer into a module with global functions that I can use anywhere in my code.

File: log.py

def enable():
    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)

enable()

Use as follows:

import log
log.info("Hello, World!")
log.err("System Error")

sty is similar to colorama, but it's less verbose, supports 8-bit and 24-bit (RGB) colors, supports all effects (bold, underline, etc.) allows you to register your own styles, is fully typed, supports muting, is really flexible, well documented and more...

Examples:

from sty import fg, bg, ef, rs

foo = fg.red + 'This is red text!' + fg.rs
bar = bg.blue + 'This has a blue background!' + bg.rs
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs

# Add custom colors:

from sty import Style, RgbFg

fg.orange = Style(RgbFg(255, 150, 50))

buf = fg.orange + 'Yay, Im orange.' + fg.rs

print(foo, bar, baz, qux, qui, buf, sep='\n')

prints:

Enter image description here

Demo:

Enter image description here


Here's a solution that works on Windows 10 natively.

Using a system call, such as os.system(""), allows colours to be printed in Command Prompt and Powershell natively:

import os

# System call
os.system("")

# Class of different styles
class style():
    BLACK = '\033[30m'
    RED = '\033[31m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'
    MAGENTA = '\033[35m'
    CYAN = '\033[36m'
    WHITE = '\033[37m'
    UNDERLINE = '\033[4m'
    RESET = '\033[0m'

print(style.YELLOW + "Hello, World!")

Note: Windows does not fully support ANSI codes, whether through system calls or modules. Not all text decoration is supported, and although the bright colours display, they are identical to the regular colours.

Thanks to @j-l for finding an even shorter method.

tl;dr: Add os.system("")


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!")

# 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))

Text with altering foreground and background, colors 0..141 Text with altering foreground and background, colors 142..255

Try it online


My favorite way is with the Blessings library (full disclosure: I wrote it). For example:

from blessings import Terminal

t = Terminal()
print t.red('This is red.')
print t.bold_bright_red_on_black('Bright red on black')

To print colored bricks, the most reliable way is to print spaces with background colors. I use this technique to draw the progress bar in nose-progressive:

print t.on_green(' ')

You can print in specific locations as well:

with t.location(0, 5):
    print t.on_yellow(' ')

If you have to muck with other terminal capabilities in the course of your game, you can do that as well. You can use Python's standard string formatting to keep it readable:

print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)

The nice thing about Blessings is that it does its best to work on all sorts of terminals, not just the (overwhelmingly common) ANSI-color ones. It also keeps unreadable escape sequences out of your code while remaining concise to use. Have fun!


YAY! Another version

While I find this answer useful, I modified it a bit. This GitHub Gist is the result

Usage

print colors.draw("i'm yellow", bold=True, fg_yellow=True)

Enter image description here

In addition, you can wrap common usages:

print colors.error('sorry, ')

Asd

https://gist.github.com/Jossef/0ee20314577925b4027f


print("\033[1;32;40m Bright Green  \n")

1


You can use the Python implementation of the curses library: curses — Terminal handling for character-cell displays

Also, run this and you'll find your box:

for i in range(255):
    print i, chr(i)

Define a string that starts a color and a string that ends the color. Then print your text with the start string at the front and the end string at the end.

CRED = '\033[91m'
CEND = '\033[0m'
print(CRED + "Error, does not compute!" + CEND)

This produces the following in Bash, in urxvt with a Zenburn-style color scheme:

Output colors

Through experimentation, we can get more colors:

Color matrix

Note: \33[5m and \33[6m are blinking.

This way we can create a full color collection:

CEND      = '\33[0m'
CBOLD     = '\33[1m'
CITALIC   = '\33[3m'
CURL      = '\33[4m'
CBLINK    = '\33[5m'
CBLINK2   = '\33[6m'
CSELECTED = '\33[7m'

CBLACK  = '\33[30m'
CRED    = '\33[31m'
CGREEN  = '\33[32m'
CYELLOW = '\33[33m'
CBLUE   = '\33[34m'
CVIOLET = '\33[35m'
CBEIGE  = '\33[36m'
CWHITE  = '\33[37m'

CBLACKBG  = '\33[40m'
CREDBG    = '\33[41m'
CGREENBG  = '\33[42m'
CYELLOWBG = '\33[43m'
CBLUEBG   = '\33[44m'
CVIOLETBG = '\33[45m'
CBEIGEBG  = '\33[46m'
CWHITEBG  = '\33[47m'

CGREY    = '\33[90m'
CRED2    = '\33[91m'
CGREEN2  = '\33[92m'
CYELLOW2 = '\33[93m'
CBLUE2   = '\33[94m'
CVIOLET2 = '\33[95m'
CBEIGE2  = '\33[96m'
CWHITE2  = '\33[97m'

CGREYBG    = '\33[100m'
CREDBG2    = '\33[101m'
CGREENBG2  = '\33[102m'
CYELLOWBG2 = '\33[103m'
CBLUEBG2   = '\33[104m'
CVIOLETBG2 = '\33[105m'
CBEIGEBG2  = '\33[106m'
CWHITEBG2  = '\33[107m'

Here is the code to generate the test:

x = 0
for i in range(24):
  colors = ""
  for j in range(5):
    code = str(x+j)
    colors = colors + "\33[" + code + "m\\33[" + code + "m\033[0m "
  print(colors)
  x = x + 5

YAY! Another version

While I find this answer useful, I modified it a bit. This GitHub Gist is the result

Usage

print colors.draw("i'm yellow", bold=True, fg_yellow=True)

Enter image description here

In addition, you can wrap common usages:

print colors.error('sorry, ')

Asd

https://gist.github.com/Jossef/0ee20314577925b4027f


If you are programming a game perhaps you would like to change the background color and use only spaces? For example:

print " "+ "\033[01;41m" + " " +"\033[01;46m"  + "  " + "\033[01;42m"

You want to learn about ANSI escape sequences. Here's a brief example:

CSI = "\x1B["
print(CSI+"31;40m" + "Colored Text" + CSI + "0m")

For more information, see ANSI escape code.

For a block character, try a Unicode character like \u2588:

print(u"\u2588")

Putting it all together:

print(CSI+"31;40m" + u"\u2588" + CSI + "0m")

For the characters

Your terminal most probably uses Unicode (typically UTF-8 encoded) characters, so it's only a matter of the appropriate font selection to see your favorite character. Unicode char U+2588, "Full block" is the one I would suggest you use.

Try the following:

import unicodedata
fp= open("character_list", "w")
for index in xrange(65536):
    char= unichr(index)
    try: its_name= unicodedata.name(char)
    except ValueError: its_name= "N/A"
    fp.write("%05d %04x %s %s\n" % (index, index, char.encode("UTF-8"), its_name)
fp.close()

Examine the file later with your favourite viewer.

For the colors

curses is the module you want to use. Check this tutorial.


There is also the Python termcolor module. Usage is pretty simple:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

Or in Python 3:

print(colored('hello', 'red'), colored('world', 'green'))

It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...


Emoji

You can use colors for text as others mentioned in their answers to have colorful text with a background or foreground color.

But you can use emojis instead! for example, you can use?? for warning messages and for error messages.

Or simply use these notebooks as a color:

: error message
: warning message
: ok status message
: action message
: canceled status message
: Or anything you like and want to recognize immediately by color

Bonus:

This method also helps you to quickly scan and find logs directly in the source code.

But some operating systems (including some Linux distributions in some version with some window managers) default emoji font is not colorful by default and you may want to make them colorful, first.


Here's a curses example:

import curses

def main(stdscr):
    stdscr.clear()
    if curses.has_colors():
        for i in xrange(1, curses.COLORS):
            curses.init_pair(i, i, curses.COLOR_BLACK)
            stdscr.addstr("COLOR %d! " % i, curses.color_pair(i))
            stdscr.addstr("BOLD! ", curses.color_pair(i) | curses.A_BOLD)
            stdscr.addstr("STANDOUT! ", curses.color_pair(i) | curses.A_STANDOUT)
            stdscr.addstr("UNDERLINE! ", curses.color_pair(i) | curses.A_UNDERLINE)
            stdscr.addstr("BLINK! ", curses.color_pair(i) | curses.A_BLINK)
            stdscr.addstr("DIM! ", curses.color_pair(i) | curses.A_DIM)
            stdscr.addstr("REVERSE! ", curses.color_pair(i) | curses.A_REVERSE)
    stdscr.refresh()
    stdscr.getch()

if __name__ == '__main__':
    print "init..."
    curses.wrapper(main)

The simplest way I can find is not to use ANSI escape codes, but use Fore from import module colorama. Take a look at the code below:

from colorama import Fore, Style

print(Fore.MAGENTA + "IZZ MAGENTA BRUH.")

print(Style.RESET_ALL + "IZZ BACK TO NORMALZ.")

compared to the ANSI escape code:

print("\u001b[31m IZZ RED (NO MAGENTA ON ANSI CODES).\u001b[0m")

print("BACK TO NORMALZ.")

This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some Python code from the Blender build scripts:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

To use code like this, you can do something like:

print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)

Or, with Python 3.6+:

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

This will work on unixes including OS X, Linux and Windows (provided you use ANSICON, or in Windows 10 provided you enable VT100 emulation). There are ANSI codes for setting the color, moving the cursor, and more.

If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "curses" module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO is a good introduction.

If you are not using extended ASCII (i.e., not on a PC), you are stuck with the ASCII characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM extended ASCII character set, you have many more options. Characters 176, 177, 178 and 219 are the "block characters".

Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the Dwarf Fortress Wiki see (user-made tilesets).

The Text Mode Demo Contest has more resources for doing graphics in text mode.


# 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))

Text with altering foreground and background, colors 0..141 Text with altering foreground and background, colors 142..255

Try it online


I created a project (console-color) and already published it to PyPI.

You can throw pip install console-color to install it.

And I write the document with Sphinx-read-the-doc, see here.

You can get more example from google-colab.

I still post some example to attract the user to click the above link:

# cprint is something like below
# cprint(text: str, fore: T_RGB = None, bg: T_RGB = None, style: Style = '')
# where T_RGB = Union[Tuple[int, int, int], str] for example. You can input (255, 0, 0) or '#ff0000' or 'ff0000'. They are OK.
# The Style you can input the ``Style.`` (the IDE will help you to choose what you wanted)

# from console_color import RGB, Fore, Style, cprint, create_print
from console_color import *

cprint("Hello, World!", RGB.RED, RGB.YELLOW, Style.BOLD+Style.URL+Style.STRIKE)
cprint("Hello, World!", fore=(255, 0, 0), bg="ffff00", style=Style.BOLD+Style.URL+Style.STRIKE)

Enter image description here

Of course, you don’t have to enter all the parameters. You can just add the attributes you want.


To be honest, this project is not special. It just uses the f"\033[{target};2;{r};{g};{b}m{text}{style}" where target is 38 or 48, text is your input string, and style is '\33[0m', '\33[1m' ... '\033[9m'. Some kind of stuff.

And I just make it easy to use (at least for me).


This is, in my opinion, the easiest method. As long as you have the RGB values of the color you want, this should work:

def colored(r, g, b, text):
    return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)

An example of printing red text:

text = 'Hello, World!'
colored_text = colored(255, 0, 0, text)
print(colored_text)

#or

print(colored(255, 0, 0, 'Hello, World! '))

Multi-colored text

text = colored(255, 0, 0, 'Hello, ') + colored(0, 255, 0, 'World')
print(text)

This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some Python code from the Blender build scripts:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

To use code like this, you can do something like:

print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)

Or, with Python 3.6+:

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

This will work on unixes including OS X, Linux and Windows (provided you use ANSICON, or in Windows 10 provided you enable VT100 emulation). There are ANSI codes for setting the color, moving the cursor, and more.

If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "curses" module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO is a good introduction.

If you are not using extended ASCII (i.e., not on a PC), you are stuck with the ASCII characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM extended ASCII character set, you have many more options. Characters 176, 177, 178 and 219 are the "block characters".

Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the Dwarf Fortress Wiki see (user-made tilesets).

The Text Mode Demo Contest has more resources for doing graphics in text mode.


Here is a simple function I use to print a text message in color without having to remember ANSI codes but rather using standard RGB tuples to define the foreground and background colors.

def print_in_color(txt_msg, fore_tuple, back_tuple, ):
    # Prints the text_msg in the foreground color specified by fore_tuple with the background specified by back_tuple
    # text_msg is the text, fore_tuple is foreground color tuple (r,g,b), back_tuple is background tuple (r,g,b)
    rf,bf,gf = fore_tuple
    rb,gb,bb = back_tuple
    msg = '{0}' + txt_msg
    mat = '\33[38;2;' + str(rf) + ';' + str(gf) + ';' + str(bf) + ';48;2;' + str(rb) + ';' +str(gb) + ';' + str(bb) + 'm'
    print(msg .format(mat))
    print('\33[0m') # Returns default print color to back to black

# Example of use using a message with variables
fore_color = 'cyan'
back_color = 'dark green'
msg = 'foreground color is {0} and the background color is {1}'.format(fore_color, back_color)
print_in_color(msg, (0,255,255), (0,127,127))

Some of the solutions like:

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)

print(fg("text", 160))

OR

def colored(r, g, b, text):
    return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)


text = 'Hello, World!'
colored_text = colored(255, 0, 0, text)
print(colored_text)

OR

class Color:
    COLOR = [f"\33[{i}m" for i in range(44)]

for i in range(44):
    print(Color.COLOR[i] + 'text')

might not work on Windows 10 terminals or PowerShell windows or their might be other cases where these might not work directly.

But on inserting, these two small lines at the beginning of the program might help:

import os
os.system('')

os.system('') allows you to print ANSI codes in the Terminal which colors your output according to your choice (but there can be other system specific functions that you might need to call, to be able to print colored text in terminal).


This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some Python code from the Blender build scripts:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

To use code like this, you can do something like:

print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)

Or, with Python 3.6+:

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

This will work on unixes including OS X, Linux and Windows (provided you use ANSICON, or in Windows 10 provided you enable VT100 emulation). There are ANSI codes for setting the color, moving the cursor, and more.

If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "curses" module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO is a good introduction.

If you are not using extended ASCII (i.e., not on a PC), you are stuck with the ASCII characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM extended ASCII character set, you have many more options. Characters 176, 177, 178 and 219 are the "block characters".

Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the Dwarf Fortress Wiki see (user-made tilesets).

The Text Mode Demo Contest has more resources for doing graphics in text mode.


I am new to Python and I'm excited every time I discover topics, like this one. But this time (suddenly) I feel like I have what to say. Especially because a few minutes ago I discovered a wow thing in Python (at least for me now):

Context Managers

from contextlib import contextmanager
# FORECOLOR
BLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'
# BACKGOUND
BLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'

@contextmanager
def printESC(prefix, color, text):
  print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')
  yield
  print("{prefix}0m".format(prefix=prefix))

with printESC('\x1B[', REDFC, 'Colored Text'):
  pass

Example

Or just like this:

# FORECOLOR
BLACKFC,REDFC,GREENFC,YELLOWFC,BLUEFC = '38;30m','38;31m','38;32m','38;33m','38;34m'
# BACKGOUND
BLACKBG,REDBG,GREENBG,YELLOWBG,BLUEBG = '48;40m','48;41m','48;42m','48;43m','48;44m'

def printESC(prefix, color, text):
  print("{prefix}{color}{text}".format(prefix=prefix, color=color, text=text), end='')
  print("{prefix}0m".format(prefix=prefix))

printESC('\x1B[', REDFC, 'Colored Text')

I suggest this new library Printy. They just released version 1.2.0 as a cross-platform library.

Check it out: Printy on GitHub

It is based on flags so you can do stuff like

from printy import printy

# With global flags, this will apply a bold (B) red (r) color and an underline (U) to the whole text
printy("Hello, World!", "rBU")

# With inline formats, this will apply a dim (D)
#blue (b) to the word 'Hello' and a stroken (S)
#yellow (y) to the word 'world', and the rest will remain as the predefined format
printy("this is a [bD]Hello@ [yS]world@ text")

Enter image description here


You could use Clint:

from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')

I ended up doing this, and 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)

I wrote a module that handles colors in Linux, OS X, and Windows. It supports all 16 colors on all platforms, you can set foreground and background colors at different times, and the string objects give sane results for things like len() and .capitalize().

https://github.com/Robpol86/colorclass

Example on Windows cmd.exe


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to terminal

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Can't compile C program on a Mac after upgrade to Mojave Flutter command not found VSCode Change Default Terminal How to switch Python versions in Terminal? How to open the terminal in Atom? Color theme for VS Code integrated terminal How to edit a text file in my terminal How to open google chrome from terminal? Switch between python 2.7 and python 3.5 on Mac OS X

Examples related to output

How to create multiple output paths in Webpack config Where does the slf4j log file get saved? CMake output/build directory Suppress console output in PowerShell Output grep results to text file, need cleaner output How to use python numpy.savetxt to write strings and float number to an ASCII file? How to read a CSV file from a URL with Python? How can I suppress column header output for a single SQL statement? How to recover closed output window in netbeans? How can I see normal print output created during pytest run?

Examples related to ansi-colors

How to print colored text to the terminal?