Color text output in Python: Colorama

by Alex
Color text output in Python: Colorama

The Colorama library allows ANSI control characters (used to create colored text in the terminal and to position the cursor) to work under MS Windows. If you find Colorama useful, don’t forget to thank its authors and make a donation. Thank you!

Installing


pip install colorama
# or
conda install -c anaconda colorama

Description

ANSI control characters have long been used to create colored text and cursor positioning in the terminal on Unix and Mac. Colorama makes it possible to use them on the Windows platform by wrapping stdout, removing the ANSI sequences found (which will look like gibberish when output), and converting them into appropriate win32 calls to change the command line state. On other platforms Colorama does not change anything. As a result, we get a simple cross-platform API for displaying colored terminal text from Python, and the following nice side effect: existing applications or libraries that use ANSI sequences to create color output on Linux or Mac can now run on Windows as well, simply by calling colorama.init(). An alternative approach is to install ansi.sys on Windows machines, which provides the same behavior for all command line applications. Colorama is designed for situations where it’s not that easy (for example, maybe your application doesn’t have an installer). The demo scripts in the library’s source code repository output small colored text using ANSI sequences. Compare their operation in Gnome-terminal and in Windows Command-Prompt, where the display is done using Colorama: ANSI-последовательности на Ubuntu под gnome-terminalANSI sequences on Ubuntu under gnome-terminalANSI-последовательности на Windows, используя ColoramaThe same ANSI sequences on Windows using Colorama These screenshots show that on Windows Colorama does not support ANSI ‘dim text’; it looks the same as ‘normal text’.

Using

Initializing

Applications must initialize Colorama using:
from colorama import init
init()
On Windows, an init() call will filter out the ANSI control sequences from any text sent to stdout or stderr and replace them with equivalent Win32 calls. On other platforms, calling init() has no effect (unless you specify other optional features; see “Init arguments,” below). By design, this behavior allows applications to call init() unconditionally on all platforms, after which ANSI output should just work. To stop using Colorama before exiting the program, simply call deinit(). This method will return stdout and stderr to their original values, so Colorama will be disabled. To reactivate it, use reinit(); this is more advantageous than calling init() again (but does the same thing).

Color output

Cross-platform display of colored text can be simplified by using constant designators for ANSI control sequences provided by the Colorama library:
from colorama import init
init()
from colorama import Fore, Back, Style
print(Fore.GREEN + ‘green text’)
print(Back.YELLOW + ‘on yellow background’)
print(Style.BRIGHT + ‘made brighter’ + Style.RESET_ALL)
print(‘plain text’)
You can also use ANSI sequences directly in your code:
print('33[31m' + 'red text')
print('33[39m') # resets to default color
Another option is to use Colorama in combination with existing ANSI libraries such as Termcolor or Blessings. This approach is highly recommended for something more than trivial text selection:
from colorama import init
from termcolor import colored
# use Colorama to make Termcolor work in Windows
init()
# now you can apply Termcolor to output
# your colored text
print(colored('Termcolor and Colorama!', 'red', 'on_yellow'))
The following formatting constants are available:
// text color
Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
//background color
Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
//text brightness and overall reset
Style: DIM, NORMAL, BRIGHT, RESET_ALL
Style.RESET_ALL resets the text, background and brightness settings. Colorama will do this reset automatically when you exit the program.

Cursor positioning

The library supports ANSI codes for changing the cursor position. See demos/demo06.py for an example.

The Init arguments

init() takes some **kwargs to override the default behavior. init(autoreset=False): If you continually reset the color settings you specify after each output, init(autoreset=True) will do this by default:
from colorama import init, Fore
init(autoreset=True)
print(Fore.GREEN + 'green text')
print('automatic return to normal')
init(strip=None): Pass True or False to determine whether ANSI codes should be stripped when output. The default behavior is to strip if the program runs on Windows or if the output is redirected (not to tty). init(convert=None): Pass True or False to determine whether to convert ANSI codes in output to win32 calls. By default Colorama will convert them if you are running on Windows and the output is on tty (terminal). init(wrap=True): On Windows, Colorama replaces sys.stdout and sys.stderr with proxy objects that override the .write() method to do their job. If this wrapper causes you problems, you can disable it by passing init(wrap=False). The default behavior is to wrap if autoreset, strip, or convert is True. When wrap is disabled, color output on platforms other than Windows will continue to work as usual. You can use the AnsiToWin32 proxy provided by Colorama directly for cross-platform color output:
import sys
from colorama import init, Fore, AnsiToWin32
init(wrap=False)
stream = AnsiToWin32(sys.stderr).stream
# Python 2
print >>stream, Fore.RED + 'red text sent to stderr'
# Python 3
print(Fore.RED + 'red text sent to stderr', file=stream)

Recognizable ANSI sequences

ANSI sequences are usually of the form:
ESC [ ; .
Where is an integer and a is a single character. Zero or more parameters are passed in. If parameters are not presented, it is usually synonymous with passing one zero. There are no spaces in the sequence; they were added here solely for readability. The only ANSI sequences that Colorama converts to win32 calls are:
ESC [ 0 m # reset all (colors and brightness)
ESC [ 1 m # bright
ESC [ 2 m # dim (looks the same as normal brightness)
ESC [ 22 m # normal brightness
# FOREGROUND (text color)
ESC [ 30 m # black
ESC [ 31 m # red
ESC [ 32 m # green
ESC [ 33 m # yellow
ESC [ 34 m # blue
ESC [ 35 m # magenta
ESC [ 36 m # cyan
ESC [ 37 m # white
ESC [ 39 m # reset
# BACKGROUND
ESC [ 40 m # black
ESC [ 41 m # red
ESC [ 42 m # green
ESC [ 43 m # yellow
ESC [ 44 m # blue
ESC [ 45 m # magenta
ESC [ 46 m # cyan
ESC [ 47 m # white
ESC [ 49 m # reset
# cursor positioning
ESC [ y;x H # position the cursor at the x, y position (y pointing down)
ESC [ y;x f # position the cursor at x, y
ESC [ n A # move the cursor up n lines
ESC [ n B # move the cursor down n lines
ESC [ n C # move the cursor n characters forward
ESC [ n D # move the cursor n characters backward
# clear the screen
ESC [ mode J # clear screen
# clear line
ESC [ mode K # clear line
Multiple numeric ‘m’ command parameters can be combined into a single sequence:
ESC [ 36 ; 45 ; 1 m # bright blue text on purple background
All other ANSI sequences like ESC [ ; … are silently removed from Windows output. Any other forms of ANSI sequences, such as single-character codes or alternate start characters, are not recognized or removed. However, it would be great to add them. You can let the developers know if it would be helpful to you via Issues on GitHub.

Current status and known issues

Personally, I’ve only tested the library on Windows XP (CMD, Console2), Ubuntu (gnome-terminal, xterm) and OS X. Some supposedly correct ANSI sequences are not recognized (see details below), but to my knowledge no one has complained about it yet. Mystery. See unsolved problems and wishlist: https://github.com/tartley/colorama/issues If you have something that doesn’t work or does not do what you expected, the authors of the library will be happy to hear about it in the problem list above, also they are happy to wait and give commit access to anyone who writes one or maybe a couple of working patches.

Related Posts

LEAVE A COMMENT