¿Cómo imprimo texto en color en el terminal?

5 minutos de lectura

avatar de usuario
aboSamoor

¿Cómo puedo enviar texto en color a la terminal en Python?

  • Este símbolo sería un gran bloque de color: El único problema es que está extendido en ASCII, tal vez puedas hacerlo funcionar usando http://stackoverflow.com/questions/8465226/using-extended-ascii-codes-with-python

    – Samie Bencherif

    5 oct 2013 a las 16:14

  • Algunos terminales también pueden mostrar caracteres Unicode. Si eso es cierto para su terminal, los caracteres posibles son casi ilimitados.

    – ay

    19 de noviembre de 2013 a las 20:02

  • Esta respuesta llegó bastante tarde, pero me parece que es la mejor… las que se votaron arriba requieren trucos especiales para Windows, mientras que esta simplemente funciona: stackoverflow.com/a/3332860/901641

    – El arte de la guerra

    16 de diciembre de 2013 a las 16:59

  • ¿Qué tal stackoverflow.com/a/42528796/610569 usando pypi.python.org/pypi/lazyme ? (descargo de responsabilidad: enchufe desvergonzado)

    – alvas

    1 de marzo de 2017 a las 10:12


  • Si no desea instalar un paquete adicional, siga esta nueva respuesta.

    – Benyamín Jafari

    24 de marzo de 2021 a las 11:41

avatar de usuario
joeld

Esto depende un poco de la plataforma en la que se encuentre. La forma más común de hacer esto es imprimiendo secuencias de escape ANSI. Para un ejemplo simple, aquí hay algo de código de Python de la Scripts de compilación de Blender:

clase bcolors: ENCABEZADO = '\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, or in Windows 10 provided you enable VT100 emulation). There are ANSI codes for setting the color, moving the cursor, and more.

If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the “curses” module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO is a good introduction.

If you are not using extended ASCII (i.e., not on a PC), you are stuck with the ASCII characters below 127, and ‘#’ or ‘@’ is probably your best bet for a block. If you can ensure your terminal is using a IBM extended ASCII character set, you have many more options. Characters 176, 177, 178 and 219 are the “block characters”.

Some modern text-based programs, such as “Dwarf Fortress”, emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the Dwarf Fortress Wiki see (user-made tilesets).

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

  • On Linux, you might want to use tput, like so since it results in more portable code.

    – Martin Ueding

    Nov 3, 2012 at 11:04

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

    Apr 9, 2014 at 6:27

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

    Sep 1, 2016 at 23:38

  • 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

    Oct 8, 2017 at 9:27

  • A good reference for how term colors work: jafrog.com/2013/11/23/colors-in-terminal.html

    – Mike Pennington

    Oct 14, 2020 at 11:02

user avatar
priestc

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

It supports Python 3.5+ as well as Python 2.7.

And as of January 2021 it is maintained.

Example screenshot:
example screenshot

  • 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

    Jul 29, 2011 at 4:16

  • Just noticed that as of 13/01/2011, it’s now under MIT license

    – Alexander Tsepkov

    Oct 28, 2011 at 2:19

  • doesn’t have unittests (unlike colorama) and not updated since 2011

    – Janus Troelsen

    Jul 20, 2013 at 19:28

  • termcolor.COLORS gives you a list of colours

    – akxlr

    Nov 14, 2015 at 2:05


  • On Windows run os.system('color') first, then the ANSI escape sequences start working.

    – Szabolcs

    Dec 12, 2018 at 16:53

user avatar
Girish Oemrawsingh

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

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[38;2;255;255;255m"

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)

  • 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

    Aug 6, 2021 at 10:09

  • @mike_rodent This isn’t *nix specific but depends on whether terminal supports ANSI

    – UltraStudioLTD

    Jan 1 at 17:37


  • 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

    Jan 15 at 10:27

  • 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

    Mar 22 at 11:42


  • @Elyasaf755 thanks, fixed it.

    – CircuitSacul

    Mar 22 at 16:36

¿Ha sido útil esta solución?

Esta web utiliza cookies propias y de terceros para su correcto funcionamiento y para fines analíticos y para mostrarte publicidad relacionada con sus preferencias en base a un perfil elaborado a partir de tus hábitos de navegación. Al hacer clic en el botón Aceptar, acepta el uso de estas tecnologías y el procesamiento de tus datos para estos propósitos. Configurar y más información
Privacidad