How to print colored text in terminal in Python?

How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?

13.11.2008 18:58:10
You should specify some additional information in order to get better responses: multiplatform? are external modules accepted?
sorin 26.08.2009 18:40:25
IPython does it, cross-platform. See what they use?
endolith 25.01.2010 03:41:38
This symbol would make a great colored block: Only problem is that it is extended ASCII, maybe you could get it to work using http://stackoverflow.com/questions/8465226/using-extended-ascii-codes-with-python
Samy Bencherif 5.10.2013 16:14:54
Some terminals also can display Unicode characters. If that is true for your terminal, the possible characters are almost unlimited.
ayke 19.11.2013 20:02:28
This answer came fairly late, but it seems to be the best to me... the ones voted above it require special hacks for Windows whereas this one just works: stackoverflow.com/a/3332860/901641
ArtOfWarfare 16.12.2013 16:59:44
30 ОТВЕТОВ

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:

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:

#
22
19.08.2015 14:33:53

You can use the Python implementation of the curses library: http://docs.python.org/library/curses.html

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

for i in range(255):
    print i, chr(i)
17
13.11.2008 19:13:59
Personally I think that the 'curses' library has been totally eclipsed by 'blessings', in the same way 'requests' has eclipsed 'urllib', etc.
Jonathan Hartley 18.08.2015 11:09:55

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 info see http://en.wikipedia.org/wiki/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")
93
11.07.2019 23:33:06
Try def d(*v): return '\x1B['+';'.join(map(str, v))+'m' then print ' '.join([d(k,i)+str(i%10)+d(0) for i in range(30,38)+range(40,48) for k in range(2)])
Evgeni Sergeev 29.12.2013 10:56:10
what is the meaning of reset here?
MohitC 26.12.2017 12:31:26

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'
    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 Python3.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.

Hmm.. I think got a little carried away on this answer. I am in the midst of planning an epic text-based adventure game, though. Good luck with your colored text!

1788
10.12.2019 19:35:12
what's the disabled used for?
cregox 11.05.2010 21:58:14
@Cawas It looks to me like it is for disabling coloring for all colors which are printed using a particular bcolors instance. For example, you could create a bcolors instance and then use the member variables of the instance to print out your coloring characters, but then if you decided you no longer wanted coloring, you could call disable before printing out the characters and they would just print out as empty strings.
Steven Oxley 15.06.2010 18:42:25
On Linux, you might want to use tput, like so since it results in more portable code.
Martin Ueding 3.11.2012 11:04:27
@Cawas: A real use case for disable is when you pipe the output to a file; while tools like cat may support colors, it is generally better to not print color information to files.
Sebastian Mach 9.04.2014 06:27:31
@AlexanderSimko, here's a ctypes code snippet to enable VT100 support in Windows 10: import ctypes; kernel32 = ctypes.WinDLL('kernel32'); hStdOut = kernel32.GetStdHandle(-11); mode = ctypes.c_ulong(); kernel32.GetConsoleMode(hStdOut, ctypes.byref(mode)); mode.value |= 4; kernel32.SetConsoleMode(hStdOut, mode).
Eryk Sun 1.09.2016 23:38:53

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"
14
24.03.2013 17:11:58
More on this can be found here- linux.byexamples.com/archives/184/…
pragmatic 8.01.2013 12:18:58

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.

3
23.11.2011 17:53:37

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)
33
8.09.2019 20:33:25
Honestly this is only solution that works with windows. All other answers are just copy of eachothers.
Danilo 25.09.2019 13:07:15
FWIW, on Windows it might be less pain to use ConEmu which supports ANSI sequences (apart from a host of other advantages over the native terminal). Still great to have a native solution though.
Endre Both 6.12.2019 10:04:22

I'm surprised no one has mentioned 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...

783
30.08.2018 18:12:32
Since it's emitting ANSI codes, does it work on Windows (DOS consoles) if ansi.sys is loaded? support.microsoft.com/kb/101875
Phil P 29.07.2011 04:16:54
Just noticed that as of 13/01/2011, it's now under MIT license
Alexander Tsepkov 28.10.2011 02:19:55
doesn't have unittests (unlike colorama) and not updated since 2011
Janus Troelsen 20.07.2013 19:28:36
termcolor.COLORS gives you a list of colours
akxlr 14.11.2015 02:05:00
On Windows run os.system('color') first, then the ANSI escape sequences start working.
Szabolcs 12.12.2018 16:53:36

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)
10
13.08.2009 12:05:41
Your code does fail under Windows (x64) with this error: AttributeError: 'module' object has no attribute 'wrapper'
sorin 25.08.2009 16:51:53
@Sorin Sbarnea: Accordingly to python curses official documentation in docs.python.org/library/curses.html , the curses module is not supported on windows. Maybe you got this error instead of "No Such Module" or something like this, because you probably named your test file "curses.py" so it is importing itself.
nosklo 25.08.2009 19:12:35

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

A Python 3.6 example screenshot: example screenshot

700
19.01.2018 17:54:39
As the author of Colorama, thanks for the mention @nbv4. I'll try and clarify a bit: Colorama aims to let Python programs print colored terminal text on all platforms, using the same ANSI codes as described in many other answers on this page. On Windows, Colorama strips these ANSI characters from stdout and converts them into equivalent win32 calls for colored text. On other platforms, Colorama does nothing. Hence you can use ANSI codes, or modules like Termcolor, and with Colorama, they 'just work' on all platforms. Is that idea, anyhow.
Jonathan Hartley 13.09.2010 13:22:19
@Jonathan, This is truly an awesome library! The ability to cross platform color Python output is really really nice and useful. I am providing tools for a library that colors its own console. I can redirect the output of that console to the terminal and colorize the output. Now I can even one up the library and let the user select colors. This will allow color blind people to set things to work so they can actually see the output correctly. Thanks
Demolishun 30.11.2012 13:05:37
This should be in the standard library... Cross platform colour support is important, I think.
daviewales 28.06.2013 14:08:41
Colorama is great! Also have a look at ansimarkup, which is built on colorama and allows you to use a simple tag-based markup (e.g. <b>bold</b>) for adding style to terminal text
gvalkov 19.02.2017 17:07:22
This doesn't work without calling colorama.init(). Vote up!
Smit Johnth 19.02.2018 03:32:03

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.

2
20.10.2011 16:34:37

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!

60
18.12.2011 00:32:49
Putting the color as a function name and not as a parameter is a questionable practice.
LtWorf 2.12.2012 14:48:38
@LtWorf: you could easily make it a parameter using getattr if you need it. Or more likely, just create the format string dynamically instead.
jfs 15.04.2014 13:58:59
@progo the fact that you can do it doesn't mean that you should do it. It's more generic if the colour is a parameter that you can just pass.
LtWorf 30.09.2015 08:00:39
You can just pass a python function.
MaxNoe 20.11.2015 22:43:17
Note that importing blessings does not work on windows so don't use it if your script needs to be cross-platform.
Adversus 26.04.2019 07:51:29

You could use CLINT:

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

Get it from GitHub.

17
23.08.2018 20:22:06
First link has gone so I removed it; the GH link is still good (although the project is "archived" and basically abandoned, from what I can gather).
Giacomo Lacava 23.08.2018 20:22:59

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.

0
25.06.2012 00:35:04

If you are using Windows, then here you go!

# display text on a Windows console
# Windows XP with Python27 or Python32
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 ... ")
11
24.03.2013 17:19:15
If you want different colors on the same line, flush the stdout stream in between calls: print("%X --> %s" % (color, "Have a fine day!"), end='', flush=True)
user2023861 14.02.2019 14:22:55

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")
18
19.01.2013 20:41:46
Tried out colorama, used print(Style.BRIGHT + "Header Test") and print (Style.DIM + word) to create a really nice prompt.
Tom 7.11.2013 16:02:15
This will need to change to use contextlib for Py3.
cat 15.01.2016 21:42:06
@cat: From what version of Python will that be necessary?
Janus Troelsen 16.01.2016 10:46:41
I believe 3 and up -- it should have a @contextlib.contextmanager decorator on it, no?
cat 16.01.2016 14:41:47
@cat: Why? Works great without.
Janus Troelsen 17.01.2016 12:42:08

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')
10
26.03.2013 21:15:20

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")
23
12.06.2013 11:38:01

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.

0
8.12.2013 07:17:37

Print a string that starts a color/style, then the string, 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 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

416
12.09.2016 17:43:54
this works in most shells as well as ipython, good enough for most applications
dashesy 18.02.2014 06:13:02
can I ask, which terminal is this?
FlipTack 3.12.2016 17:53:29
how portable is it?
Ruggero Turra 11.01.2017 21:17:41
Jonathan H 7.03.2017 15:34:21

generated a class with all the colors using a for loop to iterate every combination of color up to 100, 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'
53
11.05.2017 22:33:55

I wrote a module that handles colors in Linux/OSX/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

4
2.11.2014 01:44:34

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. I hope it will help you.

1
21.09.2017 09:59:31
Python has no \e escape sequence. Just because some echo implementations support it doesn't make those sequences universally available.
Martijn Pieters♦ 5.11.2017 12:16:23
And \e is not part of the POSIX specification for echo, so it is not universal there either. The GNU coreutils version supports it, but not the one used on OS X (a BSD variant). Last but not least, the sequence is not a shell feature either, it is specific to the echo command.
Martijn Pieters♦ 5.11.2017 12:29:29
Please see this question stackoverflow.com/questions/47121421/… which has led to these comments.
rnso 5.11.2017 13:33:08

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

Example:

print(pyfancy.RED + "Hello Red" + pyfancy.END)
3
21.09.2017 09:58:17
Not very nice code, it even contains a reference to pythonw.exe ;)
Floyd 9.04.2015 18:22:29

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

9
23.05.2017 12:10:54

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')
23
18.04.2015 22:18:35
This will crash if you pass more than one positional argument or anything other than a string type
Romain Vincent 19.03.2018 02:49:23
@RomainVincent Then don't pass more than one positional argument or anything other than a string ty— wait, these are print-replacements? Objection rescinded.
wizzwizz4 17.03.2019 20:56:23
@wizzwizz4 I'm not sure what you meant with this comment, I don't see the point anyway. If you are going to propose a class..., to replace a method as simple as print, you might as well avoid making it so easily breakable. Just my opinion.
Romain Vincent 18.03.2019 08:18:58
@RomainVincent I was going to say that your objection was wrong, but for replacing a function as versatile as print one should make sure to properly replicate its functionality.
wizzwizz4 18.03.2019 20:10:57
@RomainVincent Implements to use infinite arguments : <code> def purple(cls, *args, **kwargs): print(cls.PURPLE, *args, cls.END, **kwargs) </code>
Emilien Baudet 9.11.2019 12:51:46

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

9
22.04.2015 19:30:20

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

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

9
22.09.2017 10:23:28

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")
44
23.12.2015 20:20:49
Suggestion: define lambdas that returns that colored string, instead of printing them directly, so that it can be used in conjunction with other strings.
gustafbstrom 22.01.2016 21:40:24

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

10
5.05.2016 13:08:25