share
Stack OverflowHow do I print colored text to the terminal?
[+3256] [66] aboSamoor
[2008-11-13 18:58:10]
[ python terminal output ansi-colors ]
[ https://stackoverflow.com/questions/287871/how-do-i-print-colored-text-to-the-terminal ]

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

(1) 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-as‌​cii-codes-with-pytho‌​n - Samie Bee
(1) Some terminals also can display Unicode characters. If that is true for your terminal, the possible characters are almost unlimited. - ayke
pip install python-colored-print colored-print - Benyamin Jafari
You can use ANSI escape codes to output colored text to the terminal in Python. - Akbari
[+2946] [2008-11-13 19:25:07] joeld

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 [1]:

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 [2], or in Windows 10 provided you enable VT100 emulation [3]). 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 [4]" module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO [5] 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 [6], 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 [7] see ( user-made tilesets [8]).

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

[1] https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py
[2] https://github.com/adoxa/ansicon
[3] https://msdn.microsoft.com/en-us/library/mt638032
[4] https://en.wikipedia.org/wiki/Curses_%28programming_library%29
[5] http://docs.python.org/howto/curses.html
[6] http://telecom.tbi.net/asc-ibm.html
[7] http://dwarffortresswiki.org/DF2014:Tilesets
[8] http://dwarffortresswiki.org/Tileset_repository
[9] http://en.wikipedia.org/wiki/TMDC

But suppose my default prompt is not black - do You think it's possible to make python resotre after these tricks? - Adobe
Another useful one is UNDERLINE = '\033[4m'. What happens if ansi.sys is disabled on Windows and you try to use these ANSI escape sequences? - Dennis
(15) On Linux, you might want to use tput, like so since it results in more portable code. - Martin Ueding
(4) @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
@phresnel I see... If so I believe for this answer it should not even be mentioned as it only confuses the objectivity of it. Even if it was Steven Oxley's usage case (from the previous comment addressing this same issue) it's still the same matter. Maybe I should suggest an edit. - cregox
@joeld is it possible to do variants of one color? - Ethan Bierlein
What is the difference between the \033[ and the \x1b[ ? They seem to do the same thing - user393267
Just noting: The Python Curses module is also available in Python 3 docs.python.org/3/howto/curses.html - mike
Just noting: in windows 10, there is no need to enable ansi.sys because the terminal recognizes escape characters. - Alexander Simko
Don't just throw out terminal codes without checking the value of $TERM! Better, use a standard termcap library to refer to them by name... - Toby Speight
(2) Try this snippet to see all the colors and styles your system supports: print(''.join(['\033[' + str(x) + 'mfoo' for x in range(0,150)]) +'\033[0m') - Samie Bee
@AlexanderSimko, I'm not sure what you mean by ansi.sys. That was an MS-DOS driver. Maybe you're referring to ANSICON, which hooks and hacks the Windows console API. The Windows 10 console does natively supports VT100 emulation, but it has to be enabled. If you start Python via cmd.exe it's enabled, but this isn't the default for new consoles, such as running py.exe or python.exe by clicking on a script. - Eryk Sun
(10) @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
@newbiez There is no difference, both give the same character ESC (i.e. the character #27 in the ASCII table). 33 and 1B are simply the octal and the hexadecimal representation of the decimal number 27. - balu
(9) To anyone using the Python example code from the answer: It should be noted that the colors in the range 90-97 and 100-107 are non-standard and, indeed, on my terminal they don't all give the colors indicated by the variable names. It's better to use the standard ranges 30-37 and 40-47. Source: en.wikipedia.org/wiki/… - balu
(2) So when I run a python script with print('\033[94mfoo') in my terminal, all the text in my terminal after that is blue... How do I prevent that? - Joren
(1) @Joren You need the end the cursor with \033[0m. With the example above, appending bcolors.ENDC after a previously initiated color. - Noel
adding 1; will also make it bold. Like \033[1;Xm (where X is color code) - gjois
And how one would combine BOLD and COLOURED type? print(f'{bcolors.OKBLUE}{bcolors.BOLD}Test{bcolors.ENDC}') will display in blue but not in bold. - BayesianMonk
(1) A good reference for how term colors work: jafrog.com/2013/11/23/colors-in-terminal.html - Mike Pennington
(5) On windows, you can make ansi escape codes work by running the color command in cmd. Just put in os.system("color") - crxyz
(1) One thing to note that is important imho is that the code posted in this answer (as also stated by its author) is part of the Blender codebase. As such it is susceptible to Blender's license, which is GPL. I think the code should be changed in a way that it is not longer a problem or write own version of it. - rbaleksandar
1
[+1203] [2008-11-16 07:31:39] Samat Jain

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

from termcolor import colored

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

To get the ANSI codes working on windows, first run

os.system('color')
[1] http://pypi.python.org/pypi/termcolor

(5) 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
(46) Just noticed that as of 13/01/2011, it's now under MIT license - Alexander Tsepkov
(2) There is also chromalog which has the ability to detect the color-capability of the displaying terminal (and to eventually fall back to other decoration methods if needed). (Disclaimer: I'm the author) - ereOn
(1) Version 1.1.0 added a cprint() function: cprint('Hello, World!', 'green', 'on_red'). - dtk
(10) termcolor.COLORS gives you a list of colours - akxlr
(2) Hey Samat! Would it be nice to mention that you can still use .format() for adding variables to the printed string, like this: print(colored('{0}', 'red').format(var_with_msg)). Nice solution! Tks - ivanleoncz
(72) On Windows run os.system('color') first, then the ANSI escape sequences start working. - Szabolcs
(2) @Szabolcs You should find that you don't need that on the Windows 10 new terminal, which supports them natively. - wizzwizz4
(1) On Linux do: pip install python-termcolor - Yan King Yin
Indeed os.system('color') work, furthermore even os.system('') work well. very strange - sakiM
I created constyle github.com/abrahammurciano/python-constyle which IMO has a much neater API than termcolor - Abraham Murciano Benzadon
You can also use os.system('cls') or os.system('clear') to show ANSI colors. - Mujtaba
It seems termcolor does not support black. - tommy.carstensen
Last release: Apr 23, 2023. But yes. Was dormant from 2011 to 2022 - plswork04
termcolor is currently (2024) still actively developed again and in terms of commit activity more than `colorama - Daraan
2
[+1095] [2010-07-26 07:07:14] priestc

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

It supports Python 3.5+ as well as Python 2.7.

And as of January 2023, it is maintained.

Example Code:

from colorama import init as colorama_init
from colorama import Fore
from colorama import Style

colorama_init()

print(f"This is {Fore.GREEN}color{Style.RESET_ALL}!")

Example Screenshot: example screenshot

[1] https://pypi.python.org/pypi/colorama

(510) 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
(7) @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
(99) This should be in the standard library... Cross platform colour support is important, I think. - daviewales
(16) 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
(1) Colorama comes with Anaconda, whereas termcolor, suggested in an answer above, does not. This maked Colorama highly preferable for many Python users. - pretzlstyle
(74) This doesn't work without calling colorama.init(). Vote up! - Smit Johnth
(1) @SmitJohnth only on Windows. - Michael Leonard
@MichaelLeonard this answer shoud be crossplatform, right? - Smit Johnth
If you use the Pycharm console, calling init() on Windows will instead deactivate the colors as it already interprets the ANSI codes and ignores the win32 ones. - Leogout
@SmitJohnth, yes that would make the answer cross platform, which is unarguably good. But saying the code doesn't work without calling init() also isn't right, it works just fine on Unixy systems without it. - Michael Leonard
@SmitJohnth thanks for the additional info I was struggling to make it work on windows ! This is definetely useful and could be included in the answer. - gcharbon
Does Colorama work for JSON dumps, @JonathanHartley? - mazunki
(2) @mazunki The main purpose of Colorama is to allow existing ANSI color codes in a stream to work on Windows. Or, it also allows the author of a Python program to explicitly add their own color codes into things they print (but really, use blessings for that instead.) Colorama does not automatically 'colorize' things like JSON dumps. Use something like `pygmentize' (from Pygments) for that. - Jonathan Hartley
How do you suggest to mix both of them together? - mazunki
(1) I bet you can can use 'pygments' to add colors to some json from within a python program. Then, in the same program, import colorama and call colorama.init() so that when you print the result to stdout, it works on Windows as well as elsewhere. - Jonathan Hartley
@gvalkov thanks for the tip, love your little library. One liner highlighting is clear and concise: ansiprint(f'<bg white><blue>{h}</blue></bg white>'.join(s.split(h))) - Nathan Chappell
As suggested by @SmitJohnth, You have to run this line of code to work the above code snipped, colorama.init() - Abdul Haseeb
(1) it's an oversimplification that colorama.init() is required to work on Windows, in-fact, it may even break color output on Windows. It depends on the terminal/enviroment - CervEd
Doesn't seem to work in Powershell: ←[31mOFFLINE←[0m - Cagy79
3
[+696] [2014-02-14 17:56:38] rabin utam

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

Reference: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors


(14) this works in most shells as well as ipython, good enough for most applications - dashesy
(4) can I ask, which terminal is this? - FlipTack
(4) how portable is it? - Ruggero Turra
(3) Short standalone implementation: gist.github.com/Sheljohn/68ca3be74139f66dbc6127784f638920 - Jonathan H
@Flip This will work in any terminal/console that supports ANSI escape sequences. - wjandrea
(2) To make this work in Windows 10 Powershell, in you Python import os then do os.system('color'). From then on, ANSI escape sequences will magically work. - DoomGoober
(1) kind reminder: code begin with 5 or 6 are blinking. e.g. 5;37;41 or 6;37;41 and the last number can be reaching >=48, which is fully white background. - NegaOverflow
(1) @rabin-utam Would be nice if there was a link to these vs just screenshots - Glen Thompson
(1) @DoomGoober Running os.system('') will also work, IDK why - mousetail 'he-him'
4
[+341] [2016-09-12 14:00:32] qubodup

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

(3) What shell or terminal makes it blink? - Zypps987
(2) (u)rxvt for example - qubodup
FYI - What is labeled "beige" above is a light cyan on Apple's Terminal (and also in many other lists of color names for Python). Also, some of the double colors are light/dark versions, and the white variants I would call white and grey ... - uliwitness
(3) @captain \33[25m should also mean "Not blinking", without resetting other styles - en.wikipedia.org/wiki/… - Roland Pihlakas
(1) Turned your list into a class. Love it. Use it often. Thank you! - kevin walker
5
[+185] [2019-03-02 03:59:27] SimpleBinary

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


(3) This works - I'm really surprised that the color command enables ANSI codes in the Windows terminal, I've gone for years without knowing this was possible - the command itself doesn't give any clue that it does this. - Stuart Axon
@anaksunaman This will work on all Operating Systems that support coloured text already, as well as supporting Windows 10. - SimpleBinary
@MaxDoesStuff Really? Which Python version are you using? Also which version of MacOS? - SimpleBinary
@Nikos Sorry, I forgot to say that it only works on Windows 10. - SimpleBinary
(6) Thanks so much for your answer, @SimpleBinary! Playing around with your answer, I've found that you can simplify if sys.platform.lower() == "win32": os.system('color') even further by simply replacing it with just os.system(''). No condition is needed, and the code runs in both Windows 10 and Linux (when I tested it). As you can see, you don't have to make a system call to color. Calls to dir, cd, abcdef, and just an empty string work fine (although the non-empty strings will likely print output you don't want to see). - J-L
(4) In short, the call to color isn't the crucial part; it's the os.system(command) line itself that makes printing colors possible when running on Windows 10. And the "command" can be anything, really -- even just an empty string. - J-L
(6) this is really interesting! why does os.system("") cause color codes to work? - starwarswii
@Starwarswii Any system call seems to work. No idea why. If I find out, I'll put it on here. - SimpleBinary
(3) @Starwarswii It's not python's implementation, in C running printf(fmt, ...); with ASNI codes in windows after calling system(""); (include <stdlib.h>) does prints the color text, I'm still curious why is that? - some dev
Just some housekeeping, I would have changed the print to print(style.YELLOW + "Hello, World!" + style.RESET) - MatsK
how can I make them bold? - alper
(3) The most likely reason why os.system("") makes this work, is that it somehow enables the (Windows10) Virtual Terminal (VT) settings and UTF-8 (without BOM), when opening a pipe or console handle. Perhaps this answer is correct. You may want to experiment with setting ENABLE_VIRTUAL_TERMINAL_PROCESSING using methods from here. - not2qubit
this didnt work for me - Furkan Gözükara
6
[+116] [2008-11-13 19:22:54] Bryan Oakley

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 [1].

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")
[1] http://en.wikipedia.org/wiki/ANSI_escape_code

(4) 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
what is the meaning of reset here? - MohitC
I've been trying this solution. What is the purpose of "31;40m" and "0m"? - Qohelet
@Qohelet: did you follow the link to "ANSI escape code"? It explains how ANSI escape sequences work. The first set of numbers tell the terminal to start using a specific foreground and background color, the 0m tells the terminal to stop using that color. - Bryan Oakley
@BryanOakley - I wonder as this is not happening. Python3.7 prints it as regular text. - Qohelet
Are you running it in a terminal window that supports ANSI escape sequences? - Bryan Oakley
Compact but informative. Should be upvoted more. Quick question: There seems to be different kinds of "escape" stuff, such as ^[, \033, \u001b, \x1b (you used x1b I guess). What are the differences between them? I tried to search but not very clear. - starriet 차주녕
7
[+116] [2018-02-10 17:04:41] Rotareti

sty [1] is similar to colorama, but it's less verbose, supports 8-bit [2] and 24-bit [3] (RGB) colors, supports all effects [4] (bold, underline, etc.), allows you to register your own styles [5], is fully typed and high performant, supports muting [6], is not messing with globals such as sys.stdout, is really flexible, well documented [7] 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

[1] https://github.com/feluxe/sty
[2] https://sty.mewo.dev/docs/coloring.html#coloring-with-8-bit-codes
[3] https://sty.mewo.dev/docs/coloring.html#coloring-with-24bit-codes
[4] https://sty.mewo.dev/docs/effects.html
[5] https://sty.mewo.dev/docs/customizing.html#add-custom-styles-to-a-register-object
[6] https://sty.mewo.dev/docs/muting.html#the-mute-and-unmute-methods
[7] https://sty.mewo.dev/

(8) It would be very useful if you consider to compare it with colorama, I prefer your library, but just because more short api from the box, and it would be great if it will be more popular. Thanks! - Victor Gavro
(1) I like sty and I am trying to format my string with sty, one issue is that , when I print multiple colors, can I reset to previous color instead of default color? - intijk
@VictorGavro That's a good idea! I may add a comparison to the documentation. - Rotareti
(1) @intijk Your question doesn't really fit the comment section. For this kind of question please create a new SO Question or use the github issue tracker. - Rotareti
@intijk : use the codes fg.rs and bg.rs to reset the foreground and background colors to default, respectively. - MRule
(1) Sty is great. In my opinion it should be added to Python's standard library. - Adam Dingle
8
[+103] [2020-12-01 10:16:42] Will McGugan

Rich [1] 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 [2]-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

[1] https://github.com/willmcgugan/rich
[2] https://en.wikipedia.org/wiki/BBCode

I've been using rich for some time now and I think it can be recommended. It has great many features and offers quite many possibilities. A short example: from rich.console import Console from rich.text import Text CN = Console() title = Text() title.append(" ") title.append(" Printing colors in the terminal with \u200b", style="bold blue on white") title.append("rich", style="italic bold red on white") title.append(" \u200b", style="bold blue on white") CN.print(title, justify="center") - khaz
9
[+82] [2020-05-22 17:46:49] CircuitSacul

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 f"\033[38;2;{r};{g};{b}m{text}\033[0m"

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)

(11) This is actually the proper answer to the question and should be selected. The question is how to print colours in python and NOT what external libraries can be used. - nosbor
This printed "←[38;2;255;0;0mbubble ←[38;2;255;255;255m" when I created a red string "bubble". This is a W10 machine... is your solution *nix-specific? - mike rodent
(1) @mike_rodent This isn't *nix specific but depends on whether terminal supports ANSI - USLTD
(1) This can be further tidied using a lambda and f-strings: `coloured = lambda r, g, b, text: f'\033[38;2;{r};{g};{b}m{text} \033[38;2;255;255;255m' - P i
(1) There is a side effect trailing space after the current implementation. You can get rid of by removing the trailing space from the string format. Use this instead: f"\033[38;2;{r};{g};{b}m{text}\033[38;2;255;255;255m" - Elyasaf755
Invalid syntax for Python2 - Mehdi
(2) @Mehdi this wasn't written for python2. Almost everyone is using python3 now, and maintaining backwards compatibility isn't worth the time. If you want it to work for python2, you'll need to use .format() instead of f-strings. Hardly deserves a downvote for not working for an unsupported version of python. - CircuitSacul
(1) When terminal background color is white, exit color will cause problem. Also the exit color is hard coded, even for blackground, it will overtake user specified font color. Better change it to: return f"\033[38;2;{r};{g};{b}m{text}\033[0m". - Fisher
Why this not working for me only printing the whole string? - Peter.k
10
[+71] [2011-12-18 00:32:49] Erik Rose

My favorite way is with the Blessings [1] 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 [2]:

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!

[1] http://pypi.python.org/pypi/blessings/
[2] http://pypi.python.org/pypi/nose-progressive/

(75) Putting the color as a function name and not as a parameter is a questionable practice. - LtWorf
(1) @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
@LtWorf: why? Python's functions and methods are first-class citizens - mike3996
(10) @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
(4) You can just pass a python function. - MaxNoe
(2) Note that importing blessings does not work on windows so don't use it if your script needs to be cross-platform. - Adversus
(2) @LtWorf I disagree. (1) Use cases for passing around the color as a value are pretty rare. Typical use cases are just to use a specific color, and auto-complettion has a big practical benefit. (2) In a language that supports functions as first-class entities, having Fore.GREEN or t.on_green is equivalent, i.e., it is still possible to pass around colors. Look at how chalk does it, the best library I've ever used for colors. - bluenote10
@bluenote10 it has been 10 years since that comment. Let it go… - LtWorf
(2) @LtWorf: Apologies if my comment sounded harsh! I just wanted to offer an alternative view, to avoid readers discarding the beautiful blessings library prematurely. Cheers ;) - bluenote10
11
[+68] [2014-10-18 23:26:05] GI Jack

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'

12
[+66] [2015-12-23 20:20:49] gauravds

Try this simple code

def prRed(prt):
    print(f"\033[91m{prt}\033[00m")

def prGreen(prt):
    print(f"\033[92m{prt}\033[00m")

def prYellow(prt):
    print(f"\033[93m{prt}\033[00m")

def prLightPurple(prt):
    print(f"\033[94m{prt}\033[00m")

def prPurple(prt):
    print(f"\033[95m{prt}\033[00m")

def prCyan(prt):
    print(f"\033[96m{prt}\033[00m")

def prLightGray(prt):
    print(f"\033[97m{prt}\033[00m")

def prBlack(prt):
    print(f"\033[98m{prt}\033[00m")

def prReset(prt):
    print(f"\033[0m{prt}\033[00m")

prGreen("Hello, Green World!")
prBlack("Hello, Black World!")
prCyan("Hello, Cyan World!")
prGreen("Hello, Green World!")
prLightGray("Hello, Light Grey World!")
prLightPurple("Hello, Light Purple World!")
prPurple("Hello, Purple World!")
prRed("Hello, Red World!")
prYellow("Hello, Yellow World!")
prReset("Hello, Reset World!")

Python 3 Example Python 3 Example.

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

(30) 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
(1) Thanks @gustafbstron. This is what I decided to use: def prGreen: return '"\033[91m {}\033[00m" .format(prt) which is used like this: print(f'This will turn {prGreen("Hello world")} and change back') - MACE
13
[+47] [2018-04-25 14:50:58] Andriy Makukha
# 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 [1]

[1] https://code.labstack.com/VfphHQ14

The formatting is so nice and it has a lot of color range. I keep coming back to this, thanks! - Shane Smiskol
very nice, could you please give me some explanation about "\33[38;5;" . - Jay
(1) @Jay, this is an escape sequence. '\33' is the escape character (in octal). - Andriy Makukha
Excellent pure python solution. - n1c9
14
[+46] [2020-01-03 16:43:48] BeastCoder

I have a library called colorit [1]. 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.

[1] https://github.com/SuperMaZingCoder/ColorIt

when it will be possibility to install it with pip usage? - ncopiy
@ncopiy Hello! I am actually planning to do that within the next two days! :D For now, you can install it with the install instructions on the page. - BeastCoder
@ncopiy It is now available to be installed with pip3 (or pip). The command is pip3 install color-it or pip install color-it and can be imported with import colorit. - BeastCoder
I don't know why, but my texts are not colorized by the color provided on the Colors.etc... All my texts are turning into gray texts, but with different tone (lighter / darker)... - Victor Cordeiro Costa
@Victor Hmm, assuming you have an init_colorit() statement somewhere, it may be your terminal. What does it do in other terminals? - BeastCoder
@Victor The other might ne that whatever terminal you are using doesn't support RGB colors, in that case I can work on adding a solution. - BeastCoder
@Victor Alright, if you are still interested, I fixed the problem, it had to do with how I was initializing colorit, I ended up reverting back to the way I was doing so and removing colorama's init method. - BeastCoder
@BeastCoder It is not working at all => i.imgur.com/qGqMnxs.jpg I experienced the same issue I said before, I'm using the click library to be able to colorize my texts with success. - Victor Cordeiro Costa
15
[+41] [2008-11-13 22:22:30] orip

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 [1] from Testoob [2].

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)
[1] https://github.com/testoob/testoob/blob/master/src/testoob/reporting/colored.py
[2] https://github.com/testoob/testoob

(3) Honestly this is only solution that works with windows. All other answers are just copy of eachothers. - Danilo
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
(1) I am with Danilo. - Sorry IwontTell
(2) @Danilo notice this answer: stackoverflow.com/a/3332860/12291742 - Ekrem Dinçel
16
[+38] [2013-06-12 11:38:01] mms

I have wrapped joeld's answer [1] 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")
[1] https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-python/287944#287944

17
[+37] [2021-07-18 11:18:06] bluenote10

Here is my modern (2021) solution: yachalk [1]

It is one of the few libraries that properly supports nested styles:

enter image description here

Apart from that yachalk is auto-complete-friendly, has 256/truecolor support, comes with terminal-capability detection, and is fully typed.

Here are some design decision you may consider for choosing your solution.

High-level libraries vs low-level libraries / manual style handling?

Many answers to this question demonstrate how to ANSI escape codes directly, or suggest low-level libraries that require manual style enabling/disabling.

These approaches have subtle issues: Inserting on/off styles manually is

  • more verbose syntactically, because resets have to be specified explicitly,
  • more error prone, because you can accidentally forget to reset a style,
  • fails to get edge cases right: For instance in some terminals it is necessary to reset styles before newlines, and re-activate them after the line break. Also, some terminal have problems with simply overriding mutually exclusive styles, and require inserting "unnecessary" reset codes. If a developer's local terminal doesn't have these quirks, the developer will not discover these quirks immediately. The issue will only be reported later by others or cause problems e.g. on CI terminals.

Therefore if compatibility with many terminals is a goal, it's best to use a high-level library that offers automatic handling of style resets. This allows the library to take care of all edge cases by inserting the "spurious" ANSI escape codes where needed.

Why yet another library?

In JavaScript the de-facto standard library for the task is chalk [2], and after using it for a while in JS projects, the solutions available in the Python world were lacking in comparison. Not only is the chalk API more convenient to use (fully auto-complete compatible), it also gets all the edge cases right.

The idea of yachalk [3] is to bring the same convenience to the Python ecosystem. If you're interested in a comparison to other libraries I've started feature comparison [4] on the projects page. In addition, here is a long (but still incomplete) list of alternatives that came up during my research -- a lot to choose from :)

[1] https://github.com/bluenote10/yachalk
[2] https://github.com/chalk/chalk
[3] https://github.com/bluenote10/yachalk
[4] https://github.com/bluenote10/yachalk#prior-art-why-yet-another-chalk-clone
[5] https://pypi.org/project/colored/
[6] https://pypi.org/project/ansicolors/
[7] https://pypi.org/project/termcolor/
[8] https://pypi.org/project/colorama/
[9] https://github.com/jakob-bagterp/colorist-for-python
[10] https://pypi.org/project/sty/
[11] https://pypi.org/project/blessings/
[12] https://pypi.org/project/rich/
[13] https://pypi.org/project/colorit/
[14] https://pypi.org/project/colorprint/
[15] https://pypi.org/project/console-color/
[16] https://pypi.org/project/pyfancy/
[17] https://pypi.org/project/couleur/
[18] https://github.com/lmittmann/style
[19] https://github.com/anthonyalmarza/chalk
[20] https://pypi.org/project/simple-chalk/
[21] https://pypi.org/project/chlk/
[22] https://pypi.org/project/chalky/
[23] https://pypi.org/project/constyle

(1) But you seem to miss colorful, github.com/timofurrer/colorful - Qiulang
18
[+33] [2019-09-28 18:15:14] Vishal
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 [1]

[1] https://code.labstack.com/EoyDRCvJ

(1) Is this for python3 only? got an error on sep='' with python2 - ScipioAfricanus
(1) This should be the accepted answer for python3. Works perfectly. - vfxdev
19
[+30] [2016-08-17 20:01:56] Ben174

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 really nice for doing it without a third party package. - Jamie Counsell
20
[+27] [2008-11-13 19:06:23] UberJumper

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

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

Colors [2]

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:

#
[1] https://en.wikipedia.org/wiki/Windows_API
[2] http://www.linuxhowtos.org/Tips%20and%20Tricks/ansi_escape_sequences.htm

(1) In windows 10 colors work like linux if you call os.system('') at the beginning of your code - mousetail 'he-him'
21
[+24] [2015-04-18 22:18:35] zahanm

Stupidly simple, based on joeld's answer [1]:

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')
[1] https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-python/287944#287944

(2) This will crash if you pass more than one positional argument or anything other than a string type - Romain Vincent
@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
(1) @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
(1) @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
(1) @RomainVincent Implements to use infinite arguments : <code> def purple(cls, *args, **kwargs): print(cls.PURPLE, *args, cls.END, **kwargs) </code> - Emilien Baudet
22
[+24] [2017-03-01 10:09:35] alvas

Building on joeld's answer [1], 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

[1] https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-python/287944#287944

23
[+23] [2012-07-01 00:41:40] Janus Troelsen

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

Tried out colorama, used print(Style.BRIGHT + "Header Test") and print (Style.DIM + word) to create a really nice prompt. - Tom
This will need to change to use contextlib for Py3. - cat
@cat: From what version of Python will that be necessary? - Janus Troelsen
I believe 3 and up -- it should have a @contextlib.contextmanager decorator on it, no? - cat
(1) @cat: Why? Works great without. - Janus Troelsen
@cat That's not necessary; @contextlib.contextmanager is a shorthand for making it easier to produce context managers, but you can still use normal context managers. - wizzwizz4
24
[+21] [2012-01-08 01:40:35] Giacomo Lacava

You could use Clint [1]:

from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')
[1] https://github.com/kennethreitz/clint

(1) 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
25
[+19] [2008-11-13 19:13:59] daharon

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

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

for i in range(255):
    print i, chr(i)
[1] https://en.wikipedia.org/wiki/Curses_%28programming_library%29
[2] http://docs.python.org/library/curses.html

Personally I think that the 'curses' library has been totally eclipsed by 'blessings', in the same way 'requests' has eclipsed 'urllib', etc. - Jonathan Hartley
26
[+19] [2020-09-28 09:58:38] Mojtaba Hosseini

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.


How to open emoji picker?

mac os : [1] control + command + space

windows : [2] win + .

linux : [3] control + . or control + ;

[1] https://support.apple.com/guide/mac-help/use-emoji-and-symbols-on-mac-mchlp1560/mac
[2] https://support.microsoft.com/en-us/windows/windows-10-keyboard-tips-and-tricks-588e0b72-0fff-6d3f-aeee-6e5116097942
[3] https://www.omgubuntu.co.uk/2018/06/use-emoji-linux-ubuntu-apps

(1) This wasn't asked but I'm glad you shared it regardless! I really prefer this to text colors. - smassey
Linux? What distribution, version, and window manager? Ubuntu 20.04 (Focal Fossa)? - Peter Mortensen
Answer updated for more being precise. Thanks to point out @PeterMortensen - Mojtaba Hosseini
You say "you can use [...]" but I don't see an explanation on how to do it? Am I missing something? Any links, libraries, code, etc. explaining how to do what you mention? - hekimgil
Do you mean using emojis ? @hekimgil I have added the instruction of that - Mojtaba Hosseini
Yes. Is there a special library to put emojis or what? I don't get it? Oh, okay, now you added the emoji picker at the end of the post, thank you... How does that work though? Are the emojis posted as non-ASCII characters or are they a combination of ASCII characters that are interpreted by the displays? More information would be appreciated. - hekimgil
(2) Emojis are unicodes. you can find out more about them online by searching "emoji" 😉 - Mojtaba Hosseini
(1) There are my emoji favourites: print("❌", "ERROR:", "Cross Mark Emoji") print("✔️", "SUCCESS:", "Heavy Check Mark Emoji") - Kuba Szostak
27
[+16] [2008-11-13 19:38:57] suhib-alsisan

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"

More on this can be found here- linux.byexamples.com/archives/184/… - pragmatic
28
[+15] [2018-05-21 10:59:50] kmario23

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

color-print-python

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

Enter image description here

Results can be terminal dependant, so review the Terminal Properties section of the package documentation.

  • Windows Command Prompt and Python IDLE don't work

enter image description here

enter image description here

  • JupyterLab notebook does work

enter image description here

[1] https://pypi.org/project/termcolor/

In case if you are looking for a solution for windows 10, have as look here => stackoverflow.com/a/70599663/3057246 - Vinod Srivastav
29
[+14] [2022-06-25 08:55:14] Abhijeet

The simplest and convenient way of doing this, considering if you're writing a command-line tool. This method will work anywhere on all consoles, without installing any fancy packages.

To get the ANSI codes working on Windows, first, run os.system('color')

import os
os.system('color')

COLOR = '\033[91m'  # change it, according to the color need

END = '\033[0m'

print(COLOR + "Hello World" + END) #print a message


exit=input() #to avoid closing the terminal windows


For more colours :

enter image description here

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

Thanks to @qubodup


30
[+14] [2023-01-09 07:53:03] Federico Baù

Here a quick Class that wraps a print function for quick adding colors without installing additional packages.

(See bottom for a 2 line solution or 1 line solution ;) which is a much contained version and less verbose

Solution 1 - Proper Class

class PrintColored:
    DEFAULT = '\033[0m'
    # Styles
    BOLD = '\033[1m'
    ITALIC = '\033[3m'
    UNDERLINE = '\033[4m'
    UNDERLINE_THICK = '\033[21m'
    HIGHLIGHTED = '\033[7m'
    HIGHLIGHTED_BLACK = '\033[40m'
    HIGHLIGHTED_RED = '\033[41m'
    HIGHLIGHTED_GREEN = '\033[42m'
    HIGHLIGHTED_YELLOW = '\033[43m'
    HIGHLIGHTED_BLUE = '\033[44m'
    HIGHLIGHTED_PURPLE = '\033[45m'
    HIGHLIGHTED_CYAN = '\033[46m'
    HIGHLIGHTED_GREY = '\033[47m'

    HIGHLIGHTED_GREY_LIGHT = '\033[100m'
    HIGHLIGHTED_RED_LIGHT = '\033[101m'
    HIGHLIGHTED_GREEN_LIGHT = '\033[102m'
    HIGHLIGHTED_YELLOW_LIGHT = '\033[103m'
    HIGHLIGHTED_BLUE_LIGHT = '\033[104m'
    HIGHLIGHTED_PURPLE_LIGHT = '\033[105m'
    HIGHLIGHTED_CYAN_LIGHT = '\033[106m'
    HIGHLIGHTED_WHITE_LIGHT = '\033[107m'

    STRIKE_THROUGH = '\033[9m'
    MARGIN_1 = '\033[51m'
    MARGIN_2 = '\033[52m' # seems equal to MARGIN_1
    # colors
    BLACK = '\033[30m'
    RED_DARK = '\033[31m'
    GREEN_DARK = '\033[32m'
    YELLOW_DARK = '\033[33m'
    BLUE_DARK = '\033[34m'
    PURPLE_DARK = '\033[35m'
    CYAN_DARK = '\033[36m'
    GREY_DARK = '\033[37m'

    BLACK_LIGHT = '\033[90m'
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    PURPLE = '\033[95m'
    CYAN = '\033[96m'
    WHITE = '\033[97m'

    def __init__(self):
        self.print_original = print # old value to the original print function
        self.current_color = self.DEFAULT

    def __call__(self,
                 *values: object, sep: str | None = None,
                 end: str | None = None,
                 file: str | None = None,
                 flush: bool = False,
                 color: str|None = None,
                 default_color: str|None = None,
    ):
        if default_color:
            self.current_color = default_color

        default = self.current_color
        if color:
            values = (color, *values, default)  # wrap the content within a selected color an a default
        else:
            values = (*values, default)  # wrap the content within a selected color an a default
        self.print_original(*values, end=end, file=file, flush=flush)

Usage

class PrintColored:
    DEFAULT = '\033[0m'
    # Styles
    BOLD = '\033[1m'
    ITALIC = '\033[3m'
    UNDERLINE = '\033[4m'
    UNDERLINE_THICK = '\033[21m'
    HIGHLIGHTED = '\033[7m'
    HIGHLIGHTED_BLACK = '\033[40m'
    HIGHLIGHTED_RED = '\033[41m'
    HIGHLIGHTED_GREEN = '\033[42m'
    HIGHLIGHTED_YELLOW = '\033[43m'
    HIGHLIGHTED_BLUE = '\033[44m'
    HIGHLIGHTED_PURPLE = '\033[45m'
    HIGHLIGHTED_CYAN = '\033[46m'
    HIGHLIGHTED_GREY = '\033[47m'

    HIGHLIGHTED_GREY_LIGHT = '\033[100m'
    HIGHLIGHTED_RED_LIGHT = '\033[101m'
    HIGHLIGHTED_GREEN_LIGHT = '\033[102m'
    HIGHLIGHTED_YELLOW_LIGHT = '\033[103m'
    HIGHLIGHTED_BLUE_LIGHT = '\033[104m'
    HIGHLIGHTED_PURPLE_LIGHT = '\033[105m'
    HIGHLIGHTED_CYAN_LIGHT = '\033[106m'
    HIGHLIGHTED_WHITE_LIGHT = '\033[107m'

    STRIKE_THROUGH = '\033[9m'
    MARGIN_1 = '\033[51m'
    MARGIN_2 = '\033[52m' # seems equal to MARGIN_1
    # colors
    BLACK = '\033[30m'
    RED_DARK = '\033[31m'
    GREEN_DARK = '\033[32m'
    YELLOW_DARK = '\033[33m'
    BLUE_DARK = '\033[34m'
    PURPLE_DARK = '\033[35m'
    CYAN_DARK = '\033[36m'
    GREY_DARK = '\033[37m'

    BLACK_LIGHT = '\033[90m'
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    PURPLE = '\033[95m'
    CYAN = '\033[96m'
    WHITE = '\033[97m'

    def __init__(self):
        self.print_original = print # old value to the original print function
        self.current_color = self.DEFAULT

    def __call__(self,
                 *values: object, sep: str | None = None,
                 end: str | None = None,
                 file: str | None = None,
                 flush: bool = False,
                 color: str|None = None,
                 default_color: str|None = None,
    ):
        if default_color:
            self.current_color = default_color

        default = self.current_color
        if color:
            values = (color, *values, default)  # wrap the content within a selected color an a default
        else:
            values = (*values, default)  # wrap the content within a selected color an a default
        self.print_original(*values, end=end, file=file, flush=flush)

if __name__ == '__main__':
    print = PrintColored()

    print("Hello world - default")
    print("Hello world - Bold", color=print.BOLD)
    print("Hello world - Italic", color=print.ITALIC)
    print("Hello world - Underline", color=print.UNDERLINE)
    print("Hello world - UNDERLINE_THICK", color=print.UNDERLINE_THICK)
    print("Hello world - HighLithted", color=print.HIGHLIGHTED)
    print("Hello world - HIGHLIGHTED_BLACK", color=print.HIGHLIGHTED_BLACK)
    print("Hello world - HIGHLIGHTED_RED", color=print.HIGHLIGHTED_RED)
    print("Hello world - HIGHLIGHTED_GREEN", color=print.HIGHLIGHTED_GREEN)
    print("Hello world - HIGHLIGHTED_YELLOW", color=print.HIGHLIGHTED_YELLOW)
    print("Hello world - HIGHLIGHTED_BLUE", color=print.HIGHLIGHTED_BLUE)
    print("Hello world - HIGHLIGHTED_PURPLE", color=print.HIGHLIGHTED_PURPLE)
    print("Hello world - HIGHLIGHTED_CYAN", color=print.HIGHLIGHTED_CYAN)
    print("Hello world - HIGHLIGHTED_GREY", color=print.HIGHLIGHTED_GREY)
    print("Hello world - HIGHLIGHTED_GREY_LIGHT", color=print.HIGHLIGHTED_GREY_LIGHT)
    print("Hello world - HIGHLIGHTED_RED_LIGHT", color=print.HIGHLIGHTED_RED_LIGHT)
    print("Hello world - HIGHLIGHTED_GREEN_LIGHT", color=print.HIGHLIGHTED_GREEN_LIGHT)
    print("Hello world - HIGHLIGHTED_YELLOW_LIGHT", color=print.HIGHLIGHTED_YELLOW_LIGHT)
    print("Hello world - HIGHLIGHTED_BLUE_LIGHT", color=print.HIGHLIGHTED_BLUE_LIGHT)
    print("Hello world - HIGHLIGHTED_PURPLE_LIGHT", color=print.HIGHLIGHTED_PURPLE_LIGHT)
    print("Hello world - HIGHLIGHTED_CYAN_LIGHT", color=print.HIGHLIGHTED_CYAN_LIGHT)
    print("Hello world - HIGHLIGHTED_WHITE_LIGHT", color=print.HIGHLIGHTED_WHITE_LIGHT)
    print("Hello world - STRIKE_THROUGH", color=print.STRIKE_THROUGH)
    print("Hello world - MARGIN_1", color=print.MARGIN_1)
    print("Hello world - MARGIN_2", color=print.MARGIN_2)

    print("Hello world - BLACK", color=print.BLACK)
    print("Hello world - RED_DARK", color=print.RED_DARK)
    print("Hello world - GREEN_DARK", color=print.GREEN_DARK)
    print("Hello world - YELLOW_DARK", color=print.YELLOW_DARK)
    print("Hello world - BLUE_DARK", color=print.BLUE_DARK)
    print("Hello world - PURPLE_DARK", color=print.PURPLE_DARK)
    print("Hello world - CYAN_DARK", color=print.CYAN_DARK)
    print("Hello world - GREY_DARK", color=print.GREY_DARK)
    print("Hello world - BLACK_LIGHT", color=print.BLACK_LIGHT)
    print("Hello world - BLACK_LIGHT", color=print.BLACK_LIGHT)
    print("Hello world - RED", color=print.RED)
    print("Hello world - GREEN", color=print.GREEN)
    print("Hello world - YELLOW", color=print.YELLOW)
    print("Hello world - BLUE", color=print.BLUE)
    print("Hello world - PURPLE", color=print.PURPLE)
    print("Hello world - CYAN", color=print.CYAN)
    print("Hello world - WHITE", color=print.WHITE)

    # Back to normal
    print("", default_color=print.DEFAULT)
    print("Hello world - default")


Output

enter image description here

Solution 2 - 1/2 line solution

This can be helpful to add it especially in scripting (i.e add this at the end of script) That's because, on a script the above solution can be too verbose and really what you want to focus on is the scripting its self. Off course install a library like colorama or use this litte trick instaed

2 Line

little bit more readable, (call echo whatever you like)

DEFAULT = '\033[0m'; BOLD = '\033[1m';ITALIC = '\033[3m';UNDERLINE = '\033[4m';UNDERLINE_THICK = '\033[21m';HIGHLIGHTED = '\033[7m';HIGHLIGHTED_BLACK = '\033[40m';HIGHLIGHTED_RED = '\033[41m';HIGHLIGHTED_GREEN = '\033[42m';HIGHLIGHTED_YELLOW = '\033[43m';HIGHLIGHTED_BLUE = '\033[44m';HIGHLIGHTED_PURPLE = '\033[45m';HIGHLIGHTED_CYAN = '\033[46m';HIGHLIGHTED_GREY = '\033[47m';HIGHLIGHTED_GREY_LIGHT = '\033[100m';HIGHLIGHTED_RED_LIGHT = '\033[101m';HIGHLIGHTED_GREEN_LIGHT = '\033[102m';HIGHLIGHTED_YELLOW_LIGHT = '\033[103m';HIGHLIGHTED_BLUE_LIGHT = '\033[104m';HIGHLIGHTED_PURPLE_LIGHT = '\033[105m';HIGHLIGHTED_CYAN_LIGHT = '\033[106m';HIGHLIGHTED_WHITE_LIGHT = '\033[107m';STRIKE_THROUGH = '\033[9m';MARGIN_1 = '\033[51m';MARGIN_2 = '\033[52m';BLACK = '\033[30m';RED_DARK = '\033[31m';GREEN_DARK = '\033[32m';YELLOW_DARK = '\033[33m';BLUE_DARK = '\033[34m';PURPLE_DARK = '\033[35m';CYAN_DARK = '\033[36m';GREY_DARK = '\033[37m';BLACK_LIGHT = '\033[90m';RED = '\033[91m';GREEN = '\033[92m';YELLOW = '\033[93m';BLUE = '\033[94m';PURPLE = '\033[95m';CYAN = '\033[96m';WHITE = '\033[97m'  # noqa
echo = lambda values, color: print("%s%s%s" % (color, values, DEFAULT)) if color else print("%s%s" % (values, DEFAULT))


echo("This is red", color=RED)
echo("This is green", color=GREEN)
echo("This is cyan", color=CYAN)

1 Line

Simply copy paste this one line of code and start to use echo feature with color as you like

DEFAULT = '\033[0m'; BOLD = '\033[1m';ITALIC = '\033[3m';UNDERLINE = '\033[4m';UNDERLINE_THICK = '\033[21m';HIGHLIGHTED = '\033[7m';HIGHLIGHTED_BLACK = '\033[40m';HIGHLIGHTED_RED = '\033[41m';HIGHLIGHTED_GREEN = '\033[42m';HIGHLIGHTED_YELLOW = '\033[43m';HIGHLIGHTED_BLUE = '\033[44m';HIGHLIGHTED_PURPLE = '\033[45m';HIGHLIGHTED_CYAN = '\033[46m';HIGHLIGHTED_GREY = '\033[47m';HIGHLIGHTED_GREY_LIGHT = '\033[100m';HIGHLIGHTED_RED_LIGHT = '\033[101m';HIGHLIGHTED_GREEN_LIGHT = '\033[102m';HIGHLIGHTED_YELLOW_LIGHT = '\033[103m';HIGHLIGHTED_BLUE_LIGHT = '\033[104m';HIGHLIGHTED_PURPLE_LIGHT = '\033[105m';HIGHLIGHTED_CYAN_LIGHT = '\033[106m';HIGHLIGHTED_WHITE_LIGHT = '\033[107m';STRIKE_THROUGH = '\033[9m';MARGIN_1 = '\033[51m';MARGIN_2 = '\033[52m';BLACK = '\033[30m';RED_DARK = '\033[31m';GREEN_DARK = '\033[32m';YELLOW_DARK = '\033[33m';BLUE_DARK = '\033[34m';PURPLE_DARK = '\033[35m';CYAN_DARK = '\033[36m';GREY_DARK = '\033[37m';BLACK_LIGHT = '\033[90m';RED = '\033[91m';GREEN = '\033[92m';YELLOW = '\033[93m';BLUE = '\033[94m';PURPLE = '\033[95m';CYAN = '\033[96m';WHITE = '\033[97m';echo = lambda values, color: print("%s%s%s" % (color, values, DEFAULT)) if color else print("%s%s" % (values, DEFAULT))  # noqa


echo("This is red", color=RED)
echo("This is green", color=GREEN)
echo("This is cyan", color=CYAN)

Just what i needed hate importing library for every little thing. - Roman Toasov
@RomanToasov I think you will like what I just added in the answer. Look at solution 2. One liner or 2 line. copy paste it and boom you have it. I use it sometime especially in scripts where, you know the first solution is too big and annoying ; ) - Federico Baù
great job bro .... - Peyman Majidi
31
[+14] [2023-04-11 09:04:31] Jakob Bagterp

You can find multiple great Python packages that can solve your problem so you don't have to build it from scratch. In full disclosure, I'm the author of the Colorist [1] package. Colorist [2] is lightweight and less verbose. Simply install the package with pip install colorist and type:

from colorist import red

red("some text in red color")

some text in red color

Sometimes you may want a little more control over the terminal style, so you can also do this:

from colorist import Color

print(f"Only {Color.CYAN}this part{Color.OFF} is in colour")

Only this part is in colour

Moreover, Colorist [3] also supports color defined as RGB, HSL or Hex if your terminal supports advanced ANSI colors:

from colorist import ColorRGB, BgColorRGB

dusty_pink = ColorRGB(194, 145, 164)
bg_steel_blue = BgColorRGB(70, 130, 180)

print(f"I want to use {dusty_pink}dusty pink{dusty_pink.OFF} and {bg_steel_blue}steel blue{bg_steel_blue.OFF} colors inside this paragraph")

Examples of RGB color in terminal

from colorist import ColorHSL, BgColorHSL

mustard_green = ColorHSL(60, 56, 43)
bg_steel_gray = BgColorHSL(190, 2, 49)

print(f"I want to use {mustard_green}mustard green{mustard_green.OFF} and {bg_steel_gray}steel blue{bg_steel_gray.OFF} colors inside this paragraph")

Examples of HSL color in terminal

from colorist import ColorHex, BgColorHex

watermelon_red = ColorHex("#ff5733")
bg_mint_green = BgColorHex("#99ff99")

print(f"I want to use {watermelon_red}watermelon pink{watermelon_red.OFF} and {bg_mint_green}mint green{bg_mint_green.OFF} colors inside this paragraph")

Examples of Hex color in terminal

[1] https://jakob-bagterp.github.io/colorist-for-python/
[2] https://jakob-bagterp.github.io/colorist-for-python/
[3] https://jakob-bagterp.github.io/colorist-for-python/

(1) This is pretty cool. Minimalist as I love it. thanks for sharing. - MoonCactus
(1) Amazing, up and running in a minute. RGB colors is a killer feature. Thanks! - Anton Belonovich
32
[+12] [2012-06-25 16:59:39] navidm

If you are using Windows, then here you go!

# Display text on a Windows console
# Windows XP with Python 2.7 or Python&nbsp;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 ... ")

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
33
[+12] [2015-02-07 22:43:49] Jossef Harush Kadouri

YAY! Another version

While I find this answer [1] useful, I modified it a bit. This GitHub Gist [2] 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

[1] https://stackoverflow.com/a/26445590/3191896
[2] https://gist.github.com/Jossef/0ee20314577925b4027f

34
[+11] [2009-07-02 11:59:17] nosklo

Here's a curses [1] 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)
[1] https://en.wikipedia.org/wiki/Curses_%28programming_library%29

(1) Your code does fail under Windows (x64) with this error: AttributeError: 'module' object has no attribute 'wrapper' - sorin
(3) @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
This will always fail if the screen is not large enough (_curses.error: addwstr() returned ERR) since it will attempt to write outside the screen... (see here) - schneiderfelipe
35
[+11] [2015-04-22 19:00:32] Grijesh Chauhan

If you are using Django [1]:

>>> 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 [2]

Give it a try!!

[1] https://www.djangoproject.com/
[2] https://docs.djangoproject.com/en/1.8/topics/install/

Note that, in python3.x you should add an extra parenthesis after print: print(colorize(...)) - Benyamin Jafari
36
[+11] [2020-08-23 20:15:20] ijoseph
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) [1] has a very convenient way of doing this, and is worth considering if you're writing a command-line tool, anyway.

[1] https://click.palletsprojects.com/en/7.x/utils/

(1) Perfect, this worked for me! The color-it solution didn't work for me because my texts were not colorized by the color provided on the Colors.etc... All my texts were turning into gray texts, but with different tone (lighter / darker) - Victor Cordeiro Costa
(1) There are maybe more powerful color libraries, but this one also provides test scrolling and CL arguments autocomplete, which is perfect! - Yaroslav Nikitenko
37
[+11] [2022-01-05 21:14:49] Vinod Srivastav

ANSI Escape Codes

ANSI escape sequences are a standard for in-band signaling to control cursor location, color, font styling, and other options on video text terminals and terminal emulators. Certain sequences of bytes, most starting with an ASCII escape character and a bracket character, are embedded into text. The terminal interprets these sequences as commands, rather than text to display verbatim.

And as per the Wikipedia Article [1] we are using 38 & 48 to set the background color by passing 2;r;g;b in the below Example 1 and using the same with a twist of Html Hex colors in Example 2

enter image description here


Example 1 (RGB)

In windows 10 & other ANSI escape code supported terminals you can try this tiny script called holi.py, which works as a color mixer with values from 0-255 for Red, Green and blue:

# filename: holi.py
import os

os.system('')


def RGB(red=None, green=None, blue=None,bg=False):
    if(bg==False and red!=None and green!=None and blue!=None):
        return f'\u001b[38;2;{red};{green};{blue}m'
    elif(bg==True and red!=None and green!=None and blue!=None):
        return f'\u001b[48;2;{red};{green};{blue}m'
    elif(red==None and green==None and blue==None):
        return '\u001b[0m'

and call the RGB function to make any combination of colors as:

from holi import *


g0 = RGB()
g1 = RGB(0,255,0)
g2 = RGB(0,100,0,True)+""+RGB(100,255,100)
g3 = RGB(0,255,0,True)+""+RGB(0,50,0)

print(f"{g1}green1{g0}")
print(f"{g2}green2{g0}")
print(f"{g3}green3{g0}")

RGB() with no parameter will cleanup and set the foreground/background color to default. In case you want black you should call it as RGB(0,0,0) and for white RGB(255,255,255). While RGB(0,255,0) creates absolute green RGB(150,255,150) will produce light green.

This supports background & foreground color, to set the color as background color you must pass it with bg=True which is False by default.

For Example: To set red as the background color it should be called as RGB(255,0,0,True) but to choose red as font color just call it as RGB(255,0,0,False) since bg is by default False this simplifies to just call it as RGB(255,0,0)


Example 2 (HEX)

In case you don't what to play with 3 different values and rather use html hex colors you can try the below method

# filename: holi.py
import os

os.system('')

def HRGB(value=None,bg=False):
    if(value==None):
        return '\u001b[0m'
    
    value = value.lstrip('#')
    lv = len(value)
    rgb = tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
    if(bg==False):
        return f'\u001b[38;2;{rgb[0]};{rgb[1]};{rgb[2]}m'
    elif(bg==True):
        return f'\u001b[48;2;{rgb[0]};{rgb[1]};{rgb[2]}m'

So you can again use the same example above:

from holi import *

g0 = HRGB()
g1 = HRGB("#00FF00")
g2 = HRGB("#006400",True)+""+ HRGB("#64FF64")
g3 = HRGB("#00FF00",True)+""+ HRGB("#003200")

print(f"{g1}green1{g0}")
print(f"{g2}green2{g0}")
print(f"{g3}green3{g0}")

And it produces same result.

enter image description here


You can select either of the two version(rgb/hex) than save & import holi to get the desired effect

[1] https://en.wikipedia.org/wiki/ANSI_escape_code

(1) everyone keep in mind that these colors are terminal independent, meaning that if you want some type of green that is not from your terminal's TERM 256 colors its going to work - alexzander
I don't suppose you know how to do the same thing in Linux in gnome-terminal, or xfce4-terminal, do you? - Brōtsyorfuzthrāx
(1) All suggested solutions have their tradeoffs, but I like this one because I have full control over background and foreground colors and I don't need to install a python module. Thanks. - panofish
@Brōtsyorfuzthrāx ANSI escape codes are often used in UNIX and UNIX-like terminals, so this should work. You can read lot more about it here en.wikipedia.org/wiki/ANSI_escape_code - Vinod Srivastav
38
[+10] [2013-03-26 21:15:20] Vishal

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

39
[+10] [2015-07-09 06:58:08] drevicko

Yet another PyPI [1] 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.

[1] https://en.wikipedia.org/wiki/Python_Package_Index

40
[+10] [2016-05-05 13:08:25] jfs

asciimatics [1] 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

[1] http://asciimatics.readthedocs.io/en/stable/intro.html

41
[+10] [2021-03-24 11:40:06] Benyamin Jafari

If you want to use just built-in packages, follow this structure:

Actually, I enhanced the Mohamed Samy [1] answer which is now responsible for multiple inputs as well as numbers. Also, it supports other print() arguments such as end=. Additionally, I added a .store() method in order to write down logs into a file as well.

You can create a utility to use that anywhere into your codes:

# utility.py

from datetime import datetime

class ColoredPrint:
    def __init__(self):
        self.PINK = '\033[95m'
        self.OKBLUE = '\033[94m'
        self.OKGREEN = '\033[92m'
        self.WARNING = '\033[93m'
        self.FAIL = '\033[91m'
        self.ENDC = '\033[0m'

    def disable(self):
        self.PINK = ''
        self.OKBLUE = ''
        self.OKGREEN = ''
        self.WARNING = ''
        self.FAIL = ''
        self.ENDC = ''

    def store(self):
        date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        with open('logfile.log', mode='a') as file_:
            file_.write(f"{self.msg} -- {date}")
            file_.write("\n")

    def success(self, *args, **kwargs):
        self.msg = ' '.join(map(str, args))
        print(self.OKGREEN + self.msg + self.ENDC, **kwargs)
        return self

    def info(self, *args, **kwargs):
        self.msg = ' '.join(map(str, args))
        print(self.OKBLUE + self.msg + self.ENDC, **kwargs)
        return self

    def warn(self, *args, **kwargs):
        self.msg = ' '.join(map(str, args))
        print(self.WARNING + self.msg + self.ENDC, **kwargs)
        return self

    def err(self, *args, **kwargs):
        self.msg = ' '.join(map(str, args))
        print(self.FAIL + self.msg + self.ENDC, **kwargs)
        return self

    def pink(self, *args, **kwargs):
        self.msg = ' '.join(map(str, args))
        print(self.PINK + self.msg + self.ENDC, **kwargs)
        return self

e.g.

from utility import ColoredPrint

log = ColoredPrint()

log.success("Hello" , 123, "Bye").store()
log.info("Hello" , 123, "Bye")
log.warn("Hello" , 123, "Bye")
log.err("Hello" , 123, "Bye").store()
log.pink("Hello" , 123, "Bye")

Out:

enter image description here


[UPDATE]:

Now, its PyPI package🔗 [2] is available:

pip install python-colored-print
[1] https://stackoverflow.com/a/17064509/3702377
[2] https://github.com/agn-7/colored-print

42
[+8] [2022-06-27 07:37:49] catwith

Minimal Class:

class log:
    f = lambda color: lambda string: print(color + string + "\33[0m")

    black = f("\33[30m")
    red = f("\33[31m")
    green = f("\33[32m")
    yellow = f("\33[33m")
    blue = f("\33[34m")
    magenta = f("\33[35m")
    cyan = f("\33[36m")
    white = f("\33[37m")

# Usage
log.blue("Blue World!")

(3) Thanks, this is much cleaner than the other solutions - John von No Man
Why over complicate things with anonymous functions not everyone knows what this are or use those daily. - Roman Toasov
43
[+8] [2022-07-19 12:04:23] CPP_is_no_STANDARD

There is a more efficient way here.

# Colours
pure_red = "\033[0;31m"
dark_green = "\033[0;32m"
orange = "\033[0;33m"
dark_blue = "\033[0;34m"
bright_purple = "\033[0;35m"
dark_cyan = "\033[0;36m"
dull_white = "\033[0;37m"
pure_black = "\033[0;30m"
bright_red = "\033[0;91m"
light_green = "\033[0;92m"
yellow = "\033[0;93m"
bright_blue = "\033[0;94m"
magenta = "\033[0;95m"
light_cyan = "\033[0;96m"
bright_black = "\033[0;90m"
bright_white = "\033[0;97m"
cyan_back = "\033[0;46m"
purple_back = "\033[0;45m"
white_back = "\033[0;47m"
blue_back = "\033[0;44m"
orange_back = "\033[0;43m"
green_back = "\033[0;42m"
pink_back = "\033[0;41m"
grey_back = "\033[0;40m"
grey = '\033[38;4;236m'
bold = "\033[1m"
underline = "\033[4m"
italic = "\033[3m"
darken = "\033[2m"
invisible = '\033[08m'
reverse_colour = '\033[07m'
reset_colour = '\033[0m'
grey = "\x1b[90m"

User Manual

  • reverse_colour means that you reverse the colour that you just chose but in highlight mode (default is white).

  • pink_back (green_back etc... those with back) means that it is highlighted in pink (based on the name).

  • reset_colour resets the colour (see picture 1 for more details).

I believe I don't need to explain much more as it is listed at the variable name.

If you wish to try the code, please go to replit [1] IDE to test the code. The sample code is here [2]


Code (Picture 1):

My coding

Output (Picture 2):

Code output

[1] http://www.replit.com
[2] https://replit.com/@indexaker/Trial#main.py

44
[+7] [2008-11-13 19:53:03] tzot

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 [1] is the module you want to use. Check this tutorial [2].

[1] http://www.python.org/doc/2.5.2/lib/module-curses.html
[2] http://docs.python.org/howto/curses.html

45
[+7] [2020-04-15 00:56:32] Edgardo Obregón

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

Check it out: Printy on GitHub [1]

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

[1] https://github.com/edraobdu/printy

46
[+6] [2015-01-26 21:50:24] WebMaster

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

Example:

print(pyfancy.RED + "Hello Red" + pyfancy.END)
[1] https://github.com/ilovecode1/pyfancy

(3) Not very nice code, it even contains a reference to pythonw.exe ;) - Floyd
47
[+6] [2020-06-23 08:24:55] Carson

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

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

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

You can get more example from google-colab [3].

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

[1] https://pypi.org/project/console-color/
[2] https://carsonslovoka.github.io/console-color/en/source/introduction.html
[3] https://colab.research.google.com/drive/1cAYcC6DyiMCyD0RDcEo25LDFCh527TUQ?usp=sharing

48
[+6] [2022-10-01 10:08:12] stackunderflow

as a fan of the RGB standard, I would do it like this:

def color_text(text, rgb):
    r, g, b = rgb
    return f"\033[38;2;{r};{g};{b}m{text}\033[0m"

class rgb():
    BLACK = (0, 0, 0)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    BLUE = (0, 0, 255)
    YELLOW = (255, 255, 0)
    # and so on ...

print(color_text("hello colored world", rgb.GREEN))

PS: strongly inspired by CircuitSacul's answer


49
[+5] [2018-08-27 04:35:07] qpaycm

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 [1]

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 [2]

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')
[1] https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager
[2] https://repl.it/@VoldemarShalomo/Escape-sequences-for-visual-effects-in-terminal

50
[+5] [2021-08-11 20:02:44] ToTamire

I was moved there by google when I was looking how to color logs so:

coloredlogs

Instalation

pip install coloredlogs

Usage

Minimal usage:
import logging
import coloredlogs

coloredlogs.install()  # install a handler on the root logger

logging.debug('message with level debug')
logging.info('message with level info')
logging.warning('message with level warning')
logging.error('message with level error')
logging.critical('message with level critical')

Results with: minimal usage

Start from message level debug:
import logging
import coloredlogs

coloredlogs.install(level='DEBUG')  # install a handler on the root logger with level debug

logging.debug('message with level debug')
logging.info('message with level info')
logging.warning('message with level warning')
logging.error('message with level error')
logging.critical('message with level critical')

Results with: debug level

Hide messages from libraries:
import logging
import coloredlogs

logger = logging.getLogger(__name__)  # get a specific logger object
coloredlogs.install(level='DEBUG')  # install a handler on the root logger with level debug
coloredlogs.install(level='DEBUG', logger=logger)  # pass a specific logger object

logging.debug('message with level debug')
logging.info('message with level info')
logging.warning('message with level warning')
logging.error('message with level error')
logging.critical('message with level critical')

Results with: debug level

Format log messages:
import logging
import coloredlogs

logger = logging.getLogger(__name__)  # get a specific logger object
coloredlogs.install(level='DEBUG')  # install a handler on the root logger with level debug
coloredlogs.install(level='DEBUG', logger=logger)  # pass a specific logger object
coloredlogs.install(
    level='DEBUG', logger=logger,
    fmt='%(asctime)s.%(msecs)03d %(filename)s:%(lineno)d %(levelname)s %(message)s'
)

logging.debug('message with level debug')
logging.info('message with level info')
logging.warning('message with level warning')
logging.error('message with level error')
logging.critical('message with level critical')

Results with: format log messages

Available format attributes:
  • %(asctime)s - Time as human-readable string, when logging call was issued
  • %(created)f - Time as float when logging call was issued
  • %(filename)s - File name
  • %(funcName)s - Name of function containing the logging call
  • %(hostname)s - System hostname
  • %(levelname)s - Text logging level
  • %(levelno)s - Integer logging level
  • %(lineno)d - Line number where the logging call was issued
  • %(message)s - Message passed to logging call (same as %(msg)s)
  • %(module)s - File name without extension where the logging call was issued
  • %(msecs)d - Millisecond part of the time when logging call was issued
  • %(msg)s - Message passed to logging call (same as %(message)s)
  • %(name)s - Logger name
  • %(pathname)s - Full pathname to file containing the logging call
  • %(process)d - Process ID
  • %(processName)s - Process name
  • %(programname)s - System programname
  • %(relativeCreated)d - Time as integer in milliseconds when logging call was issued, relative to the time when logging module was loaded
  • %(thread)d - Thread ID
  • %(threadName)s - Thread name
  • %(username)s - System username

Sources:

Coloredlogs package [1]

Logging library [2]

[1] https://pypi.org/project/coloredlogs/
[2] https://docs.python.org/3/library/logging.html#logrecord-attributes

51
[+4] [2011-10-20 16:34:37] nmenezes

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.


52
[+4] [2014-11-02 01:44:34] Robpol86

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


53
[+4] [2019-12-10 19:29:25] monkey

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

54
[+4] [2020-02-16 18:54:33] Gerry P

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

55
[+4] [2020-12-28 09:40:16] Proud
print("\033[1;32;40m Bright Green  \n")

1


(3) An explanation would be in order. - Peter Mortensen
56
[+3] [2012-06-24 15:07:49] Brian M. Hunt

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

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 [2].

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

[1] https://github.com/brianmhunt/icolor
[2] https://github.com/brianmhunt/icolor/blob/master/icolor.py
[3] http://pypi.python.org/pypi/icolor/1.0

57
[+3] [2014-12-01 17:35:07] Igor Šarčević

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 [1] that can probably help you get a better grasp of this mechanism.

[1] http://shiroyasha.github.io/escape-sequences-a-quick-guide.html

Python has no \e escape sequence. Just because some echo implementations support it doesn't make those sequences universally available. - Martijn Pieters
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
Please see this question stackoverflow.com/questions/47121421/… which has led to these comments. - rnso
58
[+3] [2020-12-10 16:58:12] prerakl123

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


59
[+3] [2021-09-03 20:30:27] Sylvester is on codidact.com

You could use the pygments module to do this. For example:

from pygments import console
print(console.colorize("red", "This text is red."))

This doesn't allow you to provide a hexadecimal color for the terminal, but there are many built-in colors that you can try, like "blue", "darkgreen", "yellow", etc.


60
[+2] [2013-09-20 18:06:12] Diego Navarro

My two cents ( PyColorTerm [1]):

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.

[1] https://github.com/dnmellen/pycolorterm

61
[+2] [2021-06-25 14:46:43] Life is complex

This answer attempts to expand the concept of writing colorized text to the terminal by using a regular expression to colorize keywords in a block of text.

This answer also use the Python library Rich [1], which was briefly covered in a previous answer to this question. In this answer I use the function rich.color.ANSI_COLOR_NAMES to obtain a random list of colors that will be used to highlight predefined search terms.

import random
import re as regex
from rich import color
from rich import print


def create_dynamic_regex(search_words):
    """
    This function is used to create a dynamic regular expression
    string and a list of random colors. Both these elements will
    be used in the function colorize_text()

    :param search_words: list of search terms
    :return: regular expression search string and a list of colors
    :rtype: string, list
    """
    colors_required = create_list_of_colors(len(search_words))
    number_of_search_words = len(search_words)
    combined_string = ''
    for search_word in search_words:
        number_of_search_words -= 1
        if number_of_search_words != 0:
            current_string = ''.join(r'(\b' + search_word + r'\b)|')
            combined_string = (combined_string + current_string)
        elif number_of_search_words == 0:
            current_string = ''.join(r'(\b' + search_word + r'\b)')
            combined_string = (combined_string + current_string)
    return combined_string, colors_required


def random_color():
    """
    This function is used to create a random color using the
    Python package rich.
    :return: color name
    :rtype: string
    """
    selected_color = random.choice(list(color.ANSI_COLOR_NAMES.keys()))
    return selected_color


def create_list_of_colors(number_of_colors):
    """
    This function is used to generate a list of colors,
    which will be used in the function colorize_text()
    :param number_of_colors:
    :return: list of colors
    :rtype: list
    """
    list_of_colors = [random_color() for _ in range(number_of_colors)]
    return list_of_colors


def colorize_text(text, regex_string, array_of_colors):
    """
    This function is used to colorize specific words in a text string.
    :param text: text string potentially containing specific words to colorize.
    :param regex_string: regular expression search string
    :param array_of_colors: list of colors
    :return: colorized text
    :rtype: string
    """
    available_colors = array_of_colors
    word_regex = regex.compile(f"{regex_string}", regex.IGNORECASE)
    i = 0
    output = ""
    for word in word_regex.finditer(text):
        get_color = available_colors[word.lastindex - 1]
        output += "".join([text[i:word.start()],
                           "[%s]" % available_colors[word.lastindex - 1],
                           text[word.start():word.end()], "[/%s]" % available_colors[word.lastindex - 1]])
        i = word.end()
    return ''.join([output, text[word.end():]])


def generate_console_output(text_to_search, words_to_find):
    """
    This function is used generate colorized text that will
    be outputting to the console.

    :param text_to_search: text string potentially containing specific words to colorize.
    :param words_to_find: list of search terms.
    :return: A string containing colorized words.
    :rtype: string
    """
    search_terms, colors = create_dynamic_regex(words_to_find)
    colorize_html = colorize_text(text_to_search, search_terms, colors)
    print(colorize_html)


text = "The dog chased the cat that was looking for the mouse that the dog was playing with."
words = ['dog', 'cat', 'mouse']
generate_console_output(text, words)

Here is the print output from the code above:

enter image description here

I created two GISTs for colorizing text.

[1] https://github.com/willmcgugan/rich
[2] https://gist.github.com/johnbumgarner/035fd1dda6044a03cefca0ea1d66fbec
[3] https://gist.github.com/johnbumgarner/5f7139b00bff22d9faa6a2badcc824fe#file-colorize_keywords_in_text_html_output-py

62
[0] [2022-07-28 20:26:17] Nazime Lakehal

I wrote a library which is available on PyPI, with a simple API that follows the standard print function.

You can install it with pip install coloring.

import coloring

# Directly use print-like functions
coloring.print_red('Hello', 12)
coloring.print_green('Hey', end="", sep=";")
print()

# Get str as return
print(coloring.red('hello'))

# Use the generic colorize function
print(coloring.colorize("I'm red", "red")) # Using color names
print(coloring.colorize("I'm green", (0, 255, 0)))  # Using RGB colors
print(coloring.colorize("I'm blue", "#0000ff"))  # Using hex colors

# Or using styles (underline, bold, italic, ...)
print(coloring.colorize('Hello', 'red', s='ub'))  # underline and bold

Executed code:

enter image description here

You can check all the features here: https://github.com/Nazime/coloring.


63
[0] [2022-10-28 17:16:52] BML
class ColorText:
    """
    Use ANSI escape sequences to print colors +/- bold/underline to bash terminal.

    Examples
    --------
    >>> ColorText('HelloWorld').bold()
    >>> ColorText('HelloWorld').blue()
    >>> ColorText('HelloWorld').bold().custom("#bebebe")
    >>> ColorText('HelloWorld').underline().custom('dodgerblue')
    >>> ColorText.demo()

    Notes
    -----
    - execute ColorText.demo() for a printout of colors.
    """

    @classmethod
    def demo(cls):
        """Prints examples of all colors in normal, bold, underline, bold+underline."""
        for color in dir(ColorText):
            if all([color.startswith("_") is False,
                    color not in ["bold", "underline", "demo", "custom"],
                    callable(getattr(ColorText, color))]):
                print(getattr(ColorText(color), color)(),
                      "\t",
                      getattr(ColorText(f"bold {color}").bold(), color)(),
                      "\t",
                      getattr(ColorText(f"underline {color}").underline(), color)(),
                      "\t",
                      getattr(ColorText(f"bold underline {color}").underline().bold(), color)())
        print(ColorText("Input can also be color hex or R,G,B with ColorText.custom()").bold())
        pass

    def __init__(self, text: str = ""):
        self.text = text
        self.ending = "\033[0m"
        self.colors = []
        pass

    def __repr__(self):
        return self.text

    def __str__(self):
        return self.text

    def bold(self):
        self.text = "\033[1m" + self.text + self.ending
        return self

    def underline(self):
        self.text = "\033[4m" + self.text + self.ending
        return self

    def green(self):
        self.text = "\033[92m" + self.text + self.ending
        self.colors.append("green")
        return self

    def purple(self):
        self.text = "\033[95m" + self.text + self.ending
        self.colors.append("purple")
        return self

    def blue(self):
        self.text = "\033[94m" + self.text + self.ending
        self.colors.append("blue")
        return self

    def ltblue(self):
        self.text = "\033[34m" + self.text + self.ending
        self.colors.append("lightblue")
        return self

    def pink(self):
        self.text = "\033[35m" + self.text + self.ending
        self.colors.append("pink")
        return self

    def gray(self):
        self.text = "\033[30m" + self.text + self.ending
        self.colors.append("gray")
        return self

    def ltgray(self):
        self.text = "\033[37m" + self.text + self.ending
        self.colors.append("ltgray")
        return self

    def warn(self):
        self.text = "\033[93m" + self.text + self.ending
        self.colors.append("yellow")
        return self

    def fail(self):
        self.text = "\033[91m" + self.text + self.ending
        self.colors.append("red")
        return self

    def ltred(self):
        self.text = "\033[31m" + self.text + self.ending
        self.colors.append("lightred")
        return self

    def cyan(self):
        self.text = "\033[36m" + self.text + self.ending
        self.colors.append("cyan")
        return self

    def custom(self, *color_hex):
        """Print in custom color, `color_hex` - either actual hex, or tuple(r,g,b)"""
        if color_hex != (None, ):  # allows printing white on black background, black otherwise
            if len(color_hex) == 1:
                c = rgb2hex(colorConverter.to_rgb(color_hex[0]))
                rgb = ImageColor.getcolor(c, "RGB")
            else:
                assert (
                    len(color_hex) == 3
                ), "If not a color hex, ColorText.custom should have R,G,B as input"
                rgb = color_hex
            self.text = "\033[{};2;{};{};{}m".format(38, *rgb) + self.text + self.ending
            self.colors.append(rgb)
        return self

    pass

64
[0] [2022-11-15 01:16:49] Tim

Here's an implementation that you can use like this:

from stryle import Stryle

print(Stryle.okgreen.bold@"Hello World" + Stryle.underline@'!' + ' back to normal')
print(f"{Stryle.red}Merry {Stryle.underline.okgreen}Christmas!{Stryle.off}")
print("Merry "@Stryle.red + "Christmas"@Stryle.okgreen.underline)

enter image description here

_decorations = {
    "header" : '\033[95m',
    "okblue" : '\033[94m',
    "okcyan" : '\033[96m',
    "okgreen" : '\033[92m',
    "yellow" : '\033[93m',
    "red" : '\033[91m',
    "warning" : '\033[93m',
    "fail" : '\033[91m',
    "off" : '\033[0m',
    "bold" : '\033[1m',
    "underline" : '\033[4m',
}

class _StringStyle(str):
  def __getattribute__(self, decoration: str = _decorations["off"]):
    if decoration in _decorations:
      return _StringStyle(self.decorations + _decorations[decoration])
    return self
  def __matmul__(self, other):
    return self.decorations + str(other) + _decorations["off"]
  def __rmatmul__(self, other):
    return self.decorations + str(other) + _decorations["off"]
  def __str__(self):
    return self.decorations

Stryle = _StringStyle()

65
[0] [2024-04-30 12:25:35] Daraan

For logging I can recommend colorlog [1] which has colorama [2] as backend.

You can set up the coloring via a functions or via the logging module functions logging.dictConfig [3] and logging.fileConfig [4]

The setup is a bit more involved but nicer if you use fileConfig, howevr afterwards your log messages will be colored automatically and you do not need any more functions afterwards.

import logging
import colorlog

formatter = colorlog.ColoredFormatter(
    "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
    datefmt=None,
    reset=True,
    log_colors={
        'DEBUG':    'cyan',
        'INFO':     'green',
        'WARNING':  'yellow',
        'ERROR':    'red',
        'CRITICAL': 'red,bg_white',
    },
    secondary_log_colors={},
    style='%'
)

handler = colorlog.StreamHandler()
handler.setFormatter(formatter)

logger = logging.getLogger('example') # Note you can also use colorlog.getLogger which is the same function
logger.addHandler(handler)
[1] https://github.com/borntyping/python-colorlog
[2] https://pypi.python.org/pypi/colorama
[3] http://docs.python.org/3/library/logging.config.html#logging.config.dictConfig
[4] https://docs.python.org/3/library/logging.config.html#logging.config.fileConfig

66