How do I print colored output with Python 3?

138,763

Solution 1

It is very simple with colorama, just do this:

import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")

And here is the running result in Python3 REPL:

And call this to reset the color settings:

print(Style.RESET_ALL)

To avoid printing an empty line write this:

print(f"{Fore.BLUE}Hello World{Style.RESET_ALL}")

Solution 2

Here's a class of mine I use to color specific output in Python 3 scripts. You could import the class and use like so: from colorprint import ColorPrint as _ _.print_fail('Error occurred, quitting program')

import sys

# Colored printing functions for strings that use universal ANSI escape sequences.
# fail: bold red, pass: bold green, warn: bold yellow, 
# info: bold blue, bold: bold white

class ColorPrint:

    @staticmethod
    def print_fail(message, end = '\n'):
        sys.stderr.write('\x1b[1;31m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_pass(message, end = '\n'):
        sys.stdout.write('\x1b[1;32m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_warn(message, end = '\n'):
        sys.stderr.write('\x1b[1;33m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_info(message, end = '\n'):
        sys.stdout.write('\x1b[1;34m' + message.strip() + '\x1b[0m' + end)

    @staticmethod
    def print_bold(message, end = '\n'):
        sys.stdout.write('\x1b[1;37m' + message.strip() + '\x1b[0m' + end)

Solution 3

Put these classes into Color.py file near your test.py file and run test.py. I've tested these classes on Ubuntu Server 16.04 and Linux Mint 18.2 . All classes worked very good except GColor (RGB), that, it is usable in graphical terminal like Linux Mint terminal. Also, you can use these classes like this:

print(Formatting.Italic + ANSI_Compatible.Color(12) + "This is a " + Formatting.Bold + "test" + Formatting.Reset_Bold +  "!" + ANSI_Compatible.END + Formatting.Reset)
print(Color.B_DarkGray + Color.F_LightBlue + "This is a " + Formatting.Bold + "test" + Formatting.Reset_Bold +  "!" + Base.END)

Result:

enter image description here

Note: It's not working on Windows!

File Color.py :

class Base:
    # Foreground:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    # Formatting
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'    
    # End colored text
    END = '\033[0m'
    NC ='\x1b[0m' # No Color

class ANSI_Compatible:
    END = '\x1b[0m'
    # If Foreground is False that means color effect on Background
    def Color(ColorNo, Foreground=True): # 0 - 255
        FB_G = 38 # Effect on foreground
        if Foreground != True:
            FB_G = 48 # Effect on background
        return '\x1b[' + str(FB_G) + ';5;' + str(ColorNo) + 'm'

class Formatting:
    Bold = "\x1b[1m"
    Dim = "\x1b[2m"
    Italic = "\x1b[3m"
    Underlined = "\x1b[4m"
    Blink = "\x1b[5m"
    Reverse = "\x1b[7m"
    Hidden = "\x1b[8m"
    # Reset part
    Reset = "\x1b[0m"
    Reset_Bold = "\x1b[21m"
    Reset_Dim = "\x1b[22m"
    Reset_Italic = "\x1b[23m"
    Reset_Underlined = "\x1b[24"
    Reset_Blink = "\x1b[25m"
    Reset_Reverse = "\x1b[27m"
    Reset_Hidden = "\x1b[28m"

class GColor: # Gnome supported
    END = "\x1b[0m"
    # If Foreground is False that means color effect on Background
    def RGB(R, G, B, Foreground=True): # R: 0-255  ,  G: 0-255  ,  B: 0-255
        FB_G = 38 # Effect on foreground
        if Foreground != True:
            FB_G = 48 # Effect on background
        return "\x1b[" + str(FB_G) + ";2;" + str(R) + ";" + str(G) + ";" + str(B) + "m"

class Color:
    # Foreground
    F_Default = "\x1b[39m"
    F_Black = "\x1b[30m"
    F_Red = "\x1b[31m"
    F_Green = "\x1b[32m"
    F_Yellow = "\x1b[33m"
    F_Blue = "\x1b[34m"
    F_Magenta = "\x1b[35m"
    F_Cyan = "\x1b[36m"
    F_LightGray = "\x1b[37m"
    F_DarkGray = "\x1b[90m"
    F_LightRed = "\x1b[91m"
    F_LightGreen = "\x1b[92m"
    F_LightYellow = "\x1b[93m"
    F_LightBlue = "\x1b[94m"
    F_LightMagenta = "\x1b[95m"
    F_LightCyan = "\x1b[96m"
    F_White = "\x1b[97m"
    # Background
    B_Default = "\x1b[49m"
    B_Black = "\x1b[40m"
    B_Red = "\x1b[41m"
    B_Green = "\x1b[42m"
    B_Yellow = "\x1b[43m"
    B_Blue = "\x1b[44m"
    B_Magenta = "\x1b[45m"
    B_Cyan = "\x1b[46m"
    B_LightGray = "\x1b[47m"
    B_DarkGray = "\x1b[100m"
    B_LightRed = "\x1b[101m"
    B_LightGreen = "\x1b[102m"
    B_LightYellow = "\x1b[103m"
    B_LightBlue = "\x1b[104m"
    B_LightMagenta = "\x1b[105m"
    B_LightCyan = "\x1b[106m"
    B_White = "\x1b[107m"

And,

File test.py:

from Color import *

if __name__ == '__main__':
    print("Base:")
    print(Base.FAIL,"This is a test!", Base.END)

    print("ANSI_Compatible:")
    print(ANSI_Compatible.Color(120),"This is a test!", ANSI_Compatible.END)

    print("Formatting:")
    print(Formatting.Bold,"This is a test!", Formatting.Reset)

    print("GColor:") # Gnome terminal supported
    print(GColor.RGB(204,100,145),"This is a test!", GColor.END)

    print("Color:")
    print(Color.F_Cyan,"This is a test!",Color.F_Default)

Result:

On Ubuntu Server 16.04

Result on Ubuntu Server 16.04

On Linux Mint 18.2

Result on Linux Mint 18.2

Solution 4

Since Python is interpreted and run in C, it is possible to set colors without a module.

You can define a class for colors like this:

class color:
   PURPLE = '\033[1;35;48m'
   CYAN = '\033[1;36;48m'
   BOLD = '\033[1;37;48m'
   BLUE = '\033[1;34;48m'
   GREEN = '\033[1;32;48m'
   YELLOW = '\033[1;33;48m'
   RED = '\033[1;31;48m'
   BLACK = '\033[1;30;48m'
   UNDERLINE = '\033[4;37;48m'
   END = '\033[1;37;0m'

When writing code, you can simply write:

print(color.BLUE + "hello friends" + color.END)

Note that the color you choose will have to be capitalized like your class definition, and that these are color choices that I personally find satisfying. For a fuller array of color choices and, indeed, background choices as well, please see: https://gist.github.com/RabaDabaDoba/145049536f815903c79944599c6f952a.

This is code for C, but can easily be adapted to Python once you realize how the code is written.

Take BLUE for example, since that is what you are wanting to display.

BLUE = '033[1;37;48m'

\033 tells Python to break and pay attention to the following formatting.

1 informs the code to be bold. (I prefer 1 to 0 because it pops more.)

34 is the actual color code. It chooses blue.

48m is the background color. 48m is the same shade as the console window, so it seems there is no background.

Solution 5

# 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):
    for col in range(6):
        color = row*6 + col + 4
        if color>=0:
            text = "{:3d}".format(color)
            print (format(text,color), end=" ")
        else:
            print("   ", end=" ")

for row in range(-1,42):
    print_six(row, fg)
    print("",end=" ")
    print_six(row, bg)
    print()

# Simple usage: print(fg("text", 160))

Text with altering foreground and background, colors 0..141 Text with altering foreground and background, colors 142..255

Share:
138,763

Related videos on Youtube

javier sivira
Author by

javier sivira

Updated on February 02, 2022

Comments

  • javier sivira
    javier sivira over 2 years

    I have a simple print statement:

    print('hello friends')
    

    I would like the output to be blue in the terminal. How can I accomplish this with Python3?

  • Mohsen Abasi
    Mohsen Abasi almost 6 years
    A useful and basic and maybe complete answer from a good Linux developer.
  • Admin
    Admin over 5 years
    This is not an efficient answer. Please minimize the code to only what's needed.
  • Admin
    Admin over 5 years
    When I do that I get some interesting printout ESC[31mhelloESC[0m ESC[32mworldESC[0m
  • Admin
    Admin over 5 years
    That certainly works but converts ALL THE SCREEN to that color not just the text you are printing
  • Abdullah Noman
    Abdullah Noman over 5 years
    thats actually control function for coded character set, which works by default in common linux shells but in windows you have to enable virtual terminals to do that. @MoreInfo ECMA Standard for Control Functions
  • Abdullah Noman
    Abdullah Noman over 5 years
  • UtahJarhead
    UtahJarhead about 5 years
    Huge fan of the code exactly as is. Provides the answers I was looking for and then some.
  • Andreas detests censorship
    Andreas detests censorship about 5 years
    Only 7, 30–47 and 90–107 get coloured in Pycharm. 4 gets an underline, and 41 is pink. The two columns are identical, meaning 30–39 and 90–99 have a foreground colour, whilst 40–47 and 100–107 have background colours.
  • user1438233
    user1438233 over 4 years
    Or in one line: for i in range(256): print ('\33[38;5;'+str(i)+'m text ' + str(i) +' \33[0m')
  • Andriy Makukha
    Andriy Makukha over 4 years
    @user1438233, nice. But what I wanted to show is the period of six. Because color 166 "logically" follows color 160, and so on, while neighbouring colors like 165 and 166 could look quite different. So this demo just reveals the "structure".
  • Spencer
    Spencer over 4 years
    This works in my IDE but when I run my program via the commandline then it does not. instead a left-arrow gets printed to the terminal.
  • Fayyt
    Fayyt over 4 years
    I assume you're trying to get them to work on Windows. These color codes and Windows have a well-known and unhappy working relationship. I wish that there were a way to get the color on Windows without downloading or importing any additional modules, but the only way I know how to get these codes to work is by using the colorama module. You'll have to download the module link, and install it. Once you've done that, two lines at the top of your code should get it working, even on Windows: import colorama colorama.init() Hope that helps.
  • Itai Ganot
    Itai Ganot about 4 years
    I would go with print("{} hello friends {}".format(color.BLUE, color.END)) as it's simply more readable.
  • liv913
    liv913 about 3 years
    Hi, can you please explain what self.colorize() is? I cannot find its definition in the pasted code. Thanks in advance.
  • Math Coder 101
    Math Coder 101 almost 3 years
    The formatting tags do not work on win10, they provide color markings.