3196

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

4
  • 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-ascii-codes-with-python
    – Samie Bee
    Oct 5, 2013 at 16:14
  • 1
    Some terminals also can display Unicode characters. If that is true for your terminal, the possible characters are almost unlimited.
    – ayke
    Nov 19, 2013 at 20:02
  • pip install python-colored-print colored-print Jan 10 at 16:19
  • You can use ANSI escape codes to output colored text to the terminal in Python.
    – Akbari
    Jan 11 at 23:01

65 Answers 65

12

If you are using Windows, then here you go!

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

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

YAY! Another version

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

Usage

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

Enter image description here

In addition, you can wrap common usages:

print colors.error('sorry, ')

Asd

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

12

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 package. Colorist 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 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
  • 1
    This is pretty cool. Minimalist as I love it. thanks for sharing.
    – MoonCactus
    Apr 21, 2023 at 14:55
11

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

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


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

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

Asciicast:

rainbow-colored text among ascii noise

0
11

Here's a curses example:

import curses

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

if __name__ == '__main__':
    print "init..."
    curses.wrapper(main)
3
  • 1
    Your code does fail under Windows (x64) with this error: AttributeError: 'module' object has no attribute 'wrapper'
    – sorin
    Aug 25, 2009 at 16:51
  • 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
    Aug 25, 2009 at 19:12
  • 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) Nov 6, 2021 at 18:24
11

If you are using Django:

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

Snapshot:

Image

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

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

Give it a try!!

1
  • Note that, in python3.x you should add an extra parenthesis after print: print(colorize(...)) Nov 5, 2021 at 17:05
11
import click

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

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

2
  • 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) Aug 29, 2020 at 7:16
  • 1
    There are maybe more powerful color libraries, but this one also provides test scrolling and CL arguments autocomplete, which is perfect! Jun 16, 2022 at 10:13
11

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

4
  • 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
    Jan 8, 2022 at 16:01
  • I don't suppose you know how to do the same thing in Linux in gnome-terminal, or xfce4-terminal, do you? Oct 14, 2022 at 10:11
  • 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
    Apr 5, 2023 at 16:00
  • @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 Apr 6, 2023 at 6:57
10

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

"""
.. versionadded:: 0.9.2

Functions for wrapping strings in ANSI color codes.

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

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

    from fabric.colors import green

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

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

    from fabric.colors import red, green

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

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


def _wrap_with(code):

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

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

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

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

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

from __future__ import print_function
from colorprint import *

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

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

0
10

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

Actually, I enhanced the Mohamed Samy 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🔗 is available:

pip install python-colored-print
10

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[96m'

    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[96m'

    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)
2
  • Just what i needed hate importing library for every little thing. Feb 23 at 13:48
  • @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 ; ) Feb 24 at 11:34
8

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 IDE to test the code. The sample code is here


Code (Picture 1):

My coding

Output (Picture 2):

Code output

8

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!")
2
  • 3
    Thanks, this is much cleaner than the other solutions
    – Slothario
    Jun 29, 2022 at 21:26
  • Why over complicate things with anonymous functions not everyone knows what this are or use those daily. Feb 23 at 14:16
7

For the characters

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

Try the following:

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

Examine the file later with your favourite viewer.

For the colors

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

7

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

Check it out: Printy on GitHub

It is based on flags so you can do stuff like

from printy import printy

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

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

Enter image description here

6

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

Example:

print(pyfancy.RED + "Hello Red" + pyfancy.END)
1
  • 3
    Not very nice code, it even contains a reference to pythonw.exe ;)
    – Floyd
    Apr 9, 2015 at 18:22
6

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

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

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

You can get more example from google-colab.

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

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

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

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

Enter image description here

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


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

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

6

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

5

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

Context Managers

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

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

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

Example

Or just like this:

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

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

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

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

Logging library

4

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.

0
4

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.")
4
print("\033[1;32;40m Bright Green  \n")

1

1
  • 3
    An explanation would be in order. Jan 9, 2021 at 22:54
4

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

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

0
3

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

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

from icolor import cformat # there is also cprint

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

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

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

One can escape # with ##.

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

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

3

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

0
3

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

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

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

Or from a Python script:

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

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

3
  • Python has no \e escape sequence. Just because some echo implementations support it doesn't make those sequences universally available.
    – Martijn Pieters
    Nov 5, 2017 at 12:16
  • 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
    Nov 5, 2017 at 12:29
  • Please see this question stackoverflow.com/questions/47121421/… which has led to these comments.
    – rnso
    Nov 5, 2017 at 13:33
3

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

from pygments import console
print(pygments.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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.