Цветной вывод текста в Python
Всем привет сегодня я хотел рассказать вам «Как сделать цветной вывод текста в Python?» это даже может сделать не опытный человек не имея каких-то знаний. Поэтому если вам интересно то продолжайте читать и тогда все поймете.
C помощью встроенных средств языка
На Python с помощью ANSI-код можно делать цвет, фон и т.д. Это очень мощный и удобный инструмент, с его помощью программист может напрямую определять цвет текста. ANSI коды работают на большинстве дистрибутивов Linux, но не поддерживаются консолью операционной системы Windows до Windows 10.
Изменять цвет текста с помощью ANSI кодов можно разными способами, например, использоваться функции или даже написать свой класс-обёртку для ANSI.
Использовать ANSI коды просто, для этого нужно знать базовый синтаксис и сами коды. Разбор на примере кода «\033[31m\033[43m»:
-
«033[» — обозначение того, что дальше идет какой-то управляющий цветом код.
-
37m — это код цвета а именно красный.
-
43m — это код цвет фона для текста.
Именно через этот ANSI-код мы можем делать текст разноцветным, не забывайте ставить ""
иначе будет ошибка.
Давайте сделаем вывод текста на консоле через функции.
def out_red(text):
print("\033[34m{}".format(text))
out_red("ПРИВЕТ")
Через print() мы задали цвет текста «ПРИВЕТ» синим цветом. Также можно добавить фон и стиль текста все в одну строку.
print("\033[3m\033[33m\033[41m{}\033[0m".format("Htua_0111100000"))
-
\033[3m — отвечает за стилб текста в данном случае это курсив.
-
\033[33m — отвечает за цвет текста.
-
\033[41m — отвечает за цвет фона.
-
{} — заменит на «Htua_0111100000»
-
\033[0m — отвечает за сброс к начальным значениям.
Вобщем вот целая таблица с кодами цвета, фона и стилей.
Цвет |
Текст |
Фон |
Чёрный |
30 |
40 |
Красный |
31 |
41 |
Зелёный |
32 |
42 |
Жёлтый |
33 |
43 |
Синий |
34 |
44 |
Фиолетовый |
35 |
45 |
Бирюзовый |
36 |
46 |
Белый |
37 |
47 |
Код |
Стили текста |
|
0 |
Сброс к начальным значениям |
|
1 |
Жирный |
|
2 |
Блёклый |
|
3 |
Курсив |
|
4 |
Подчёркнутый |
|
5 |
Редкое мигание |
|
6 |
Частое мигание |
|
7 |
Смена цвета фона с цветом текста |
Цветной вывод текста в Python через библиотеку Colorama
Этой библиотекой тоже можно сделать цветной текст. Достаточно просто знать код и все. Для того чтобы начать работать нужно просто установить библиотеку pip install colorama
потом можно начать работать с этой библиотекой. Создайте файл colorama.py и можно приступать к написанию кода.
from colorama import init, Fore
from colorama import Back
from colorama import Style
init(autoreset=True)
print(Fore.BLUE + 'some red text')
print(Back.WHITE + 'and with a green background')
print(Style.BRIGHT + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
-
Cначала импортируем
init, Back, Style
то есть все необходимые нам функции для вывода текста на консоль. -
Стоит обратить внимание на функцию
init
. Если её забыть запустить, то не будет поддерживаться вывод на Windows 10. -
print(Fore.BLUE + 'some red text')
— это задает цвет текста также вы можете поменять на красный (RED) или зеленный (GREEN) и т.д. -
print(Back.WHITE + 'and with a green background')
— это задает фон текста -
print(Style.BRIGHT + 'and in dim text')
— стиль текста -
print(Style.RESET_ALL)
— сброс всех стилей -
print('back to normal now')
— обычный текст
Цветной текст через библиотеку termcolor
Это тоже вторая библиотека отвечающее за цвет фон и так далее. pip install termcolor
from termcolor import colored, cprint
print(colored('Привет мир!', 'red', attrs=['underline']))
print('Привет, я люблю тебя!')
cprint('Вывод с помощью cprint', 'green', 'on_blue')
Импортируем colored и cprint, и пишем print(colored('Привет мир!', 'red', attrs=['underline']))
тут вобще намного легче чем предыдущая attrs = [‘underline’] задает стиль текста. Следущее сpint('Вывод с помощью cprint', 'green', 'on_blue')
— это функция отвечает за цвет текста и фон.сpint('Ваш любимый текст', 'цвет текста', 'фон текста')
Вывод
В общем, благодаря ANSI-кодом, библиотека colorama и termcolor можно создавать ваши любимые тексты, кстати можно с этой темой можно создавать мини викторины или что то другое. Я надеюсь на то что вам понравилось эта статья и надеюсь в будущем я продолжу писать все больше и больше статей на разные темы. Спасибо за внимание!
Last Updated :
27 Jun, 2022
In this article, we will cover how to print colored text in Python using several methods to output colored text to the terminal in Python.
The most common ways to do this are using:
- Using colorama Module
- Using termcolor Module
- Using ANSI Code in Python
Method 1: Print Color Text using colorama Module
Colorama module is a Cross-platform printing of colored text can then be done using Colorama’s constant shorthand for ANSI escape sequences:
Example 1: Python program to print red text with green background.
Python3
from colorama import Fore, Back, Style print(Fore.RED + 'some red text') print(Back.GREEN + 'and with a green background') print(Style.DIM + 'and in dim text') print(Style.RESET_ALL) print('back to normal now')
Output:
Example 2: Python program to print green text with red background.
Python3
from colorama import init from termcolor import colored init() print(colored('Hello, World!', 'green', 'on_red'))
Output:
Method 2: Print Color Text using termcolor Module
termcolor module is a python module for ANSII Color formatting for output in the terminal.
Example: Python program to print colored text and background.
Python3
import sys from termcolor import colored, cprint text = colored('Hello, World!', 'red', attrs=['reverse', 'blink']) print(text) cprint('Hello, World!', 'green', 'on_red') def print_red_on_cyan(x): return cprint(x, 'red', 'on_cyan') print_red_on_cyan('Hello, World!') print_red_on_cyan('Hello, Universe!') for i in range(10): cprint(i, 'magenta', end=' ') cprint("Attention!", 'red', attrs=['bold'], file=sys.stderr)
Output:
Method 3: Print Color Text using ANSI Code in Python
The most common way to print colored text is by printing ANSI escape sequences directly. This can be delivered in different formats such as:
Example 1: Build Functions to call
We can build functions to call particular color named functions to execute the relevant ANSI Escape Sequence. The below is Python program to print colored text and background
Python3
def prRed(skk): print("\033[91m {}\033[00m" .format(skk)) def prGreen(skk): print("\033[92m {}\033[00m" .format(skk)) def prYellow(skk): print("\033[93m {}\033[00m" .format(skk)) def prLightPurple(skk): print("\033[94m {}\033[00m" .format(skk)) def prPurple(skk): print("\033[95m {}\033[00m" .format(skk)) def prCyan(skk): print("\033[96m {}\033[00m" .format(skk)) def prLightGray(skk): print("\033[97m {}\033[00m" .format(skk)) def prBlack(skk): print("\033[98m {}\033[00m" .format(skk)) prCyan("Hello World, ") prYellow("It's") prGreen("Geeks") prRed("For") prGreen("Geeks")
Output:
Example 2: Build a class of colors
Create a class to allot background and foreground colors and call them. The below is Python program to print colored text and background.
Python3
class colors: '''Colors class:reset all colors with colors.reset; two sub classes fg for foreground and bg for background; use as colors.subclass.colorname. i.e. colors.fg.red or colors.bg.greenalso, the generic bold, disable, underline, reverse, strike through, 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' print(colors.bg.green, "SKk", colors.fg.red, "Amartya") print(colors.bg.lightgrey, "SKk", colors.fg.red, "Amartya")
Output:
Example 3: Iterating functions
We can design iterating & self-generating ANSI Escape sequence, functions. The below is Python program to print colored text and background
Python3
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()
Output:
Introduction
If you’ve ever worked with some fany command-line tools, you might have seen some colored
text in there — maybe for a warning or error message or somesuch. It certainly can help
in reading comprehension in some situations, so how can we do it in Python?
Specifically, Python 3.8.5 on a Windows 10 machine.
Coloring Terminal Text in Python
The library that is recommended (especially for cross-platform use) is Colorama. This StackOverflow answer suggested its use.
Installing Colorama
Colorama didn’t come pre-installed, but pip saved me:
C:\Users\sfrieder>pip3 install colorama
Collecting colorama
Downloading https://files.pythonhosted.org/packages/c9/dc/45cdef1b4d119eb96316b3117e6d5708a08029992b2fee2c143c7a0a5cc5/colorama-0.4.3-py2.py3-none-any.whl
Installing collected packages: colorama
Successfully installed colorama-0.4.3
Coloring ‘print’ Statements Example
This Python 3 snippet will color text for you:
import colorama
colorama.init()
print(colorama.Fore.RED + "This is red text")
print("This is still red text")
print(colorama.Style.RESET_ALL) #This prints a newline FYI!
print("Now this is normal text")
print(colorama.Back.GREEN + "Now the background of this text is green")
print(colorama.Fore.RED + "And the text is red on a green background, this clashes so bad!")
print(colorama.Style.DIM + "It's now also... dimmed? What's that?")
print(colorama.Style.RESET_ALL)
print("Thank goodness, back to normal")
And it produces this output:
This is red text
This is still red text
Now this is normal text
Now the background of this text is green
And the text is red on a green background, this clashes so bad!
It's now also... dimmed? What's that?
Thank goodness, back to normal
Eh… trust me. It’s colored. I cannot figure out how to get that to come through here, but it is I swear!
Coloring ‘input’ Statements Example
If you do something like this:
import colorama
colorama.init()
answer=input(colorama.Fore.RED + "This is a dire question, so it is colored red. What is your name?" + colorama.Style.RESET_ALL)
You do NOT get a red colored question prompt. You get gobbledy-gook at the front and end of the line, but no colors.
The question is, how do you fix this?
Someone suggests this fix:
import colorama
colorama.init(convert=True)
answer=input(colorama.Fore.RED + "This is a dire question, so it is colored red. What is your quest?" + colorama.Style.RESET_ALL)
Sadly, this does not work.
This SO answer suggests a truly confounding fix:
import colorama
import sphinx.quickstart
colorama.init()
answer=input(colorama.Fore.RED + "This is a dire question, so it is colored red. What is your favorite color?" + colorama.Style.RESET_ALL)
I had to install sphinx with pip to even get it to run. It installed a LOT of stuff. Once that was done, the result was…
That it still couldn’t find sphinx.quickstart.
Grumble grumble….
Okay, we can try something else:
import colorama
import sphinx.quickstart
colorama.init()
print(colorama.Fore.RED, end='')
answer=input(This is a dire question, so it is colored red. What is the air speed velocity of an unladen swallow?" )
print(colorama.Style.RESET_ALL, end='')
And THAT has the intended effect!
What a silly workaround.
Resources
- Colorama
- StackOverflow Answer for print statements
- StackOverflow Question for ‘input’ not working with colors
Makes ANSI escape character sequences (for producing colored terminal text and
cursor positioning) work under MS Windows.
PyPI for releases |
Github for source |
Colorama for enterprise on Tidelift
If you find Colorama useful, please to the authors. Thank you!
Installation
Tested on CPython 2.7, 3.7, 3.8, 3.9 and 3.10 and Pypy 2.7 and 3.8.
No requirements other than the standard library.
pip install colorama
# or
conda install -c anaconda colorama
Description
ANSI escape character sequences have long been used to produce colored terminal
text and cursor positioning on Unix and Macs. Colorama makes this work on
Windows, too, by wrapping stdout, stripping ANSI sequences it finds (which
would appear as gobbledygook in the output), and converting them into the
appropriate win32 calls to modify the state of the terminal. On other platforms,
Colorama does nothing.
This has the upshot of providing a simple cross-platform API for printing
colored terminal text from Python, and has the happy side-effect that existing
applications or libraries which use ANSI sequences to produce colored output on
Linux or Macs can now also work on Windows, simply by calling
colorama.just_fix_windows_console() (since v0.4.6) or colorama.init()
(all versions, but may have other side-effects – see below).
An alternative approach is to install ansi.sys on Windows machines, which
provides the same behaviour for all applications running in terminals. Colorama
is intended for situations where that isn’t easy (e.g., maybe your app doesn’t
have an installer.)
Demo scripts in the source code repository print some colored text using
ANSI sequences. Compare their output under Gnome-terminal’s built in ANSI
handling, versus on Windows Command-Prompt using Colorama:
These screenshots show that, on Windows, Colorama does not support ANSI ‘dim
text’; it looks the same as ‘normal text’.
Usage
Initialisation
If the only thing you want from Colorama is to get ANSI escapes to work on
Windows, then run:
from colorama import just_fix_windows_console
just_fix_windows_console()
If you’re on a recent version of Windows 10 or better, and your stdout/stderr
are pointing to a Windows console, then this will flip the magic configuration
switch to enable Windows’ built-in ANSI support.
If you’re on an older version of Windows, and your stdout/stderr are pointing to
a Windows console, then this will wrap sys.stdout and/or sys.stderr in a
magic file object that intercepts ANSI escape sequences and issues the
appropriate Win32 calls to emulate them.
In all other circumstances, it does nothing whatsoever. Basically the idea is
that this makes Windows act like Unix with respect to ANSI escape handling.
It’s safe to call this function multiple times. It’s safe to call this function
on non-Windows platforms, but it won’t do anything. It’s safe to call this
function when one or both of your stdout/stderr are redirected to a file – it
won’t do anything to those streams.
Alternatively, you can use the older interface with more features (but also more
potential footguns):
from colorama import init
init()
This does the same thing as just_fix_windows_console, except for the
following differences:
-
It’s not safe to call init multiple times; you can end up with multiple
layers of wrapping and broken ANSI support. -
Colorama will apply a heuristic to guess whether stdout/stderr support ANSI,
and if it thinks they don’t, then it will wrap sys.stdout and
sys.stderr in a magic file object that strips out ANSI escape sequences
before printing them. This happens on all platforms, and can be convenient if
you want to write your code to emit ANSI escape sequences unconditionally, and
let Colorama decide whether they should actually be output. But note that
Colorama’s heuristic is not particularly clever. -
init also accepts explicit keyword args to enable/disable various
functionality – see below.
To stop using Colorama before your program exits, simply call deinit().
This will restore stdout and stderr to their original values, so that
Colorama is disabled. To resume using Colorama again, call reinit(); it is
cheaper than calling init() again (but does the same thing).
Most users should depend on colorama >= 0.4.6, and use
just_fix_windows_console. The old init interface will be supported
indefinitely for backwards compatibility, but we don’t plan to fix any issues
with it, also for backwards compatibility.
Colored Output
Cross-platform printing of colored text can then be done using Colorama’s
constant shorthand for ANSI escape sequences. These are deliberately
rudimentary, see below.
from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
…or simply by manually printing ANSI sequences from your own code:
print('\033[31m' + 'some red text')
print('\033[39m') # and reset to default color
…or, Colorama can be used in conjunction with existing ANSI libraries
such as the venerable Termcolor
the fabulous Blessings,
or the incredible _Rich.
If you wish Colorama’s Fore, Back and Style constants were more capable,
then consider using one of the above highly capable libraries to generate
colors, etc, and use Colorama just for its primary purpose: to convert
those ANSI sequences to also work on Windows:
SIMILARLY, do not send PRs adding the generation of new ANSI types to Colorama.
We are only interested in converting ANSI codes to win32 API calls, not
shortcuts like the above to generate ANSI characters.
from colorama import just_fix_windows_console
from termcolor import colored
# use Colorama to make Termcolor work on Windows too
just_fix_windows_console()
# then use Termcolor for all colored text output
print(colored('Hello, World!', 'green', 'on_red'))
Available formatting constants are:
Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Style: DIM, NORMAL, BRIGHT, RESET_ALL
Style.RESET_ALL resets foreground, background, and brightness. Colorama will
perform this reset automatically on program exit.
These are fairly well supported, but not part of the standard:
Fore: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX Back: LIGHTBLACK_EX, LIGHTRED_EX, LIGHTGREEN_EX, LIGHTYELLOW_EX, LIGHTBLUE_EX, LIGHTMAGENTA_EX, LIGHTCYAN_EX, LIGHTWHITE_EX
Cursor Positioning
ANSI codes to reposition the cursor are supported. See demos/demo06.py for
an example of how to generate them.
Init Keyword Args
init() accepts some **kwargs to override default behaviour.
- init(autoreset=False):
-
If you find yourself repeatedly sending reset sequences to turn off color
changes at the end of every print, then init(autoreset=True) will
automate that:from colorama import init init(autoreset=True) print(Fore.RED + 'some red text') print('automatically back to default color again')
- init(strip=None):
-
Pass True or False to override whether ANSI codes should be
stripped from the output. The default behaviour is to strip if on Windows
or if output is redirected (not a tty). - init(convert=None):
-
Pass True or False to override whether to convert ANSI codes in the
output into win32 calls. The default behaviour is to convert if on Windows
and output is to a tty (terminal). - init(wrap=True):
-
On Windows, Colorama works by replacing sys.stdout and sys.stderr
with proxy objects, which override the .write() method to do their work.
If this wrapping causes you problems, then this can be disabled by passing
init(wrap=False). The default behaviour is to wrap if autoreset or
strip or convert are True.When wrapping is disabled, colored printing on non-Windows platforms will
continue to work as normal. To do cross-platform colored output, you can
use Colorama’s AnsiToWin32 proxy directly:import sys from colorama import init, AnsiToWin32 init(wrap=False) stream = AnsiToWin32(sys.stderr).stream # Python 2 print >>stream, Fore.BLUE + 'blue text on stderr' # Python 3 print(Fore.BLUE + 'blue text on stderr', file=stream)
Recognised ANSI Sequences
ANSI sequences generally take the form:
ESC [ <param> ; <param> ... <command>
Where <param> is an integer, and <command> is a single letter. Zero or
more params are passed to a <command>. If no params are passed, it is
generally synonymous with passing a single zero. No spaces exist in the
sequence; they have been inserted here simply to read more easily.
The only ANSI sequences that Colorama converts into win32 calls are:
ESC [ 0 m # reset all (colors and brightness) ESC [ 1 m # bright ESC [ 2 m # dim (looks same as normal brightness) ESC [ 22 m # normal brightness # FOREGROUND: 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 cursor at x across, y down ESC [ y;x f # position cursor at x across, y down ESC [ n A # move cursor n lines up ESC [ n B # move cursor n lines down ESC [ n C # move cursor n characters forward ESC [ n D # move cursor n characters backward # clear the screen ESC [ mode J # clear the screen # clear the line ESC [ mode K # clear the line
Multiple numeric params to the ‘m’ command can be combined into a single
sequence:
ESC [ 36 ; 45 ; 1 m # bright cyan text on magenta background
All other ANSI sequences of the form ESC [ <param> ; <param> … <command>
are silently stripped from the output on Windows.
Any other form of ANSI sequence, such as single-character codes or alternative
initial characters, are not recognised or stripped. It would be cool to add
them though. Let me know if it would be useful for you, via the Issues on
GitHub.
Status & Known Problems
I’ve personally only tested it on Windows XP (CMD, Console2), Ubuntu
(gnome-terminal, xterm), and OS X.
Some valid ANSI sequences aren’t recognised.
If you’re hacking on the code, see README-hacking.md. ESPECIALLY, see the
explanation there of why we do not want PRs that allow Colorama to generate new
types of ANSI codes.
See outstanding issues and wish-list:
https://github.com/tartley/colorama/issues
If anything doesn’t work for you, or doesn’t do what you expected or hoped for,
I’d love to hear about it on that issues list, would be delighted by patches,
and would be happy to grant commit access to anyone who submits a working patch
or two.
License
Copyright Jonathan Hartley & Arnon Yaari, 2013-2020. BSD 3-Clause license; see
LICENSE file.
Professional support
Professional support for colorama is available as part of the |
Thanks
See the CHANGELOG for more thanks!
-
Marc Schlaich (schlamar) for a setup.py fix for Python2.5.
-
Marc Abramowitz, reported & fixed a crash on exit with closed stdout,
providing a solution to issue #7’s setuptools/distutils debate,
and other fixes. -
User ‘eryksun’, for guidance on correctly instantiating ctypes.windll.
-
Matthew McCormick for politely pointing out a longstanding crash on non-Win.
-
Ben Hoyt, for a magnificent fix under 64-bit Windows.
-
Jesse at Empty Square for submitting a fix for examples in the README.
-
User ‘jamessp’, an observant documentation fix for cursor positioning.
-
User ‘vaal1239’, Dave Mckee & Lackner Kristof for a tiny but much-needed Win7
fix. -
Julien Stuyck, for wisely suggesting Python3 compatible updates to README.
-
Daniel Griffith for multiple fabulous patches.
-
Oscar Lesta for a valuable fix to stop ANSI chars being sent to non-tty
output. -
Roger Binns, for many suggestions, valuable feedback, & bug reports.
-
Tim Golden for thought and much appreciated feedback on the initial idea.
-
User ‘Zearin’ for updates to the README file.
-
John Szakmeister for adding support for light colors
-
Charles Merriam for adding documentation to demos
-
Jurko for a fix on 64-bit Windows CPython2.5 w/o ctypes
-
Florian Bruhin for a fix when stdout or stderr are None
-
Thomas Weininger for fixing ValueError on Windows
-
Remi Rampin for better Github integration and fixes to the README file
-
Simeon Visser for closing a file handle using ‘with’ and updating classifiers
to include Python 3.3 and 3.4 -
Andy Neff for fixing RESET of LIGHT_EX colors.
-
Jonathan Hartley for the initial idea and implementation.
Overview
- Introduction
- Color text with ANSI escape characters
- Install colorama
- Clear the screen
- Change text style
- Turn on auto-reset
- Colorama alternatives
- Conclusion
- Reference links
Introduction
This tutorial covers how to use standard ANSI escape codes to colorize and style terminal output. We’ll cover the basics of escape characters, using them to clear the screen and set foreground and background colors, and how to get them working in Windows using the colorama package.
If you write an application that supports color, keep in mind that not every terminal supports the color characters. Consider adding an option with your program to toggle color output on or off, otherwise people who have no color will see all the escape characters and the output will be ugly and hard to read.
In Windows 10, some color escape codes are supported without any special configuration. Read more at MSDN Console Virtual Terminal Sequences. It is not full curses support but some colors and cursor control abilities work.
Color text with ANSI escape characters
You can manually colorizing output by using escape characters. This is quite tedious and ugly, but possible. The big catch here is that these ANSI escape characters don’t work in Windows. Don’t worry though, we’ll cover how to get them working in Windows below!. This will work on ANSI consoles like Linux shells, but not in Windows. Windows has their own escape characters. Here are some simple examples to show how the escape characters can be used with the print() function in Python.
# In Python, print red text using ANSI escape codes
# Doesn't work well in Windows though
print('\033[2J') # Clear screen
print('\033[31m' + 'Hello' + '\033[0m') # Red textThe \033 is how the escape character is represented in Python, which is then followed by a special code. The 033 is the octal value of the escape character code, 27. Sometimes it is represented as \x1b which is the hexadecimal equivalent for 27. In the bash shell, you might see the escape character represented by \e in codes that look like \e[31m. You may have seen these codes if you have ever tried to customize your PS1 prompt shell in bash. The \033 just designated that the values coming directly after it are special characters meant to be interpeted by the terminal. We typically pass color codes right after the escape character to change the color text being output, but there are also special characters to clear the screen or move the cursor.
The [31m part of \033[31m means «red foreground mode». All escape codes start with a an open bracket [ but not all of them end with an m. For example, [2J is the code to clear the screen and [3D will move the cursor back 3 characters. The m in [31m is because we are toggling graphics mode 31 (red foreground).
You can try these yourself and see how they works. Your results may vary. Since this is unreliable, we’ll look at the colorama Python package which has a bunch of shortcuts for these hard-to-remember codes, and also enables these ANSI codes on Windows, making colorized code more portable.
Install colorama package
The colorama package will abstract away the Windows specific stuff and let you use regular ANSI color codes. It also provides convenient Python utilities for coloring text in an easy way that works across all platforms.
pyhon -m pip install colorama
Clear the screen
Once you initialize colorama you can start passing ANSI codes. You can manually print out the escape character \033 followed by the code for clear screen which is [2J and it will clear the screen. Colorama also provides a convenience function that will return the value you need to print to clear the screen. The example below shows both options.
import colorama
colorama.init()
# Print the clear screen code '\033[2J'
print('\033[2J')# Or use the colorama provided function which
# returns an equivalent value '\x1b[2J'
print(colorama.ansi.clear_screen())Change text style
After installing the colorama package, you can use it inside your Python programs like this:
import colorama
# If using Windows, init() will cause anything sent to stdout or stderr
# will have ANSI color codes converted to the Windows versions. Hooray!
# If you are already using an ANSI compliant shell, it won't do anything
colorama.init()# Now regular ANSI codes should work, even in Windows
CLEAR_SCREEN = '\033[2J'
RED = '\033[31m' # mode 31 = red forground
RESET = '\033[0m' # mode 0 = reset
print(CLEAR_SCREEN + RED + 'Welcome!' + RESET)The example above shows how to import colorama and initialize it. Initializing it will add a filter on stdout and stderr which causes any ANSI escape characters be converted to the Windows equivalent. This is neat because it will also work if you have aother packages or code that outputs typical ANSI color characters. The author of colorama mentions termcolor as an option that you can use in tandem with colorama.
Colorama does provide a better way to output colors though. You don’t need to use the ugly escape characters manually. It has some named values for the colors and styles. The example below shows how to use the friendly shortcuts provided by colorama to change text style.
import colorama
from colorama import Fore, Back, Style
colorama.init()# Set the color semi-permanently
print(Fore.CYAN)
print("Text will continue to be cyan")
print("until it is reset or changed")
print(Style.RESET_ALL)# Colorize a single line and then reset
print(Fore.RED + 'You can colorize a single line.' + Style.RESET_ALL)# Colorize a single word in the output
print('Or a single ' + Back.GREEN + 'words' + Style.RESET_ALL + ' can be highlighted')# Combine foreground and background color
print(Fore.BLUE + Back.WHITE)
print('Foreground, background, and styles can be combined')
print("========== ")print(Style.RESET_ALL)
print('If unsure, reset everything back to normal.')For a full list of foreground, background, and style options, refer to the official colorama GitHub page. Here’s a quick list:
Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Style: DIM, NORMAL, BRIGHT, RESET_ALLNote that not all of them may be supported by all terminals. For example Windows does not support dim. For a full list of the codes, check out ANSI escape code list. On that Wikipedia page it is the «SGR (Select Graphic Rendition) parameters» section that I linked to. Code 0 should look familiar, it is the reset value. 30-37 will set a foreground color, 40-47 will set background color. Not every code is supported by every terminal, and note every code is handled by colorama’s Windows converter.
Turn on auto-reset
If you don’t want to print Style.RESET_ALL all the time, you can have it reset automatically after each print statement.
import colorama
from colorama import Fore, Backcolorama.init(autoreset=True)
# Automatically adds a Style.RESET_ALL after each print statement
print(Fore.RED + 'Red foreground text')
print(Back.RED + 'Red background text')
print("Some plain text")Colorama alternatives
Since colorama just takes advantage of ANSI standard escape characters, any other library that makes use of this standard can be used. These are not strictly replacements or alternatives because many of them can be used in tandem with colorama since colorama’s main purpose is to convert the ANSI codes in to proper Window’s equivalents enabling all the typical terminal control utilities. Here are some links to other resources you might find useful:
- termcolor package
- Blessings package
- Urwid website
- Curtsies
- Curses Programming with Python
- Curses in Windows with Python
Conclusion
After reading this you should understand how basic ANSI escape codes are used to change the color of text in the terminal. You should also know how to get it working in Windows. You should be able to clear the screen, change forground and background color, and reset the styles of text. To take it further, you can look in to the curses library which will allow you to control the screen even more. If you want to learn more about how the terminal works, you can check out this good PyCon talk: Thomas Ballinger — Terminal whispering — PyCon 2015.
Reference links
- MSDN Console Virtual Terminal Sequences
- Curses Programming with Python
- colorama on PyPI.org
- colorama GitHub page
- Curses Programming with Python (Official docs)
- Curses in Windows
- ANSI escape code list
- Thomas Ballinger — Terminal whispering — PyCon 2015
- Curtsies
- termcolor package
- Blessings package
- Urwid website