22

I just installed termcolor for Python 2.7 on Windows. When I try to print colored text, I get the color codes instead.

from termcolor import colored
print colored('Text text text', 'red')

Here is the result:

Screenshot of the Windows console window with the line: "←31mText text text←[0m"

I obtain the same results on Far Manager and when I tried to run the script as a standalone application.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
user3170921
  • 383
  • 1
  • 2
  • 9

9 Answers9

52

To make the ANSI colors used in termcolor work with the windows terminal, you'll need to also import/init colorama;

>>> from termcolor import *
>>> cprint('hello', 'red')
←[31mhello←[0m
>>> import colorama
>>> colorama.init()
>>> cprint('hello', 'red')
hello                                    <-- in red color
>>>
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
12

windows command prompt uses a command to change the terminal output colour. you can execute the command 'color color-code' to change the color instantly. Just having the command color activates this color feature.

In short.. For your script to work, Run this at the start of your script.

import os
os.system('color')
Tarun Sethupat
  • 146
  • 1
  • 5
3

In termcolor2 module you must type this:

import termcolor2
import colorama
colorama.init()

myText = input("Type a text : ")
color = input("What color you want? : ")

print(termcolor2.colored(myText, color))

That's it...

Morteza Rahmani
  • 516
  • 6
  • 7
1

Did work :

inserting previous to importing termcolor:

import subprocess
subprocess.call('', shell=True)

Didn't work:

  1. importing colorama (didn't) fix problem - still shows characters
  2. importing / using termcolor2 (didn't) fix problem - still shows
    characters
  3. importing colorama AND termcolor2 AND termcolor (didn't) fix problem.

Can't explain why it works, only that I was able to compare one script that colors worked correctly, and one that didn't work correctly.

Community
  • 1
  • 1
1

A very Simple solution is make one class that defines colors and use it in a function, You do not have to import any module just copy it and paste it:-

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'


def c_print(color, text):
    if color == "green":
        return print(bcolors.OKGREEN + text + bcolors.ENDC)
    if color == "cyan":
        return print(bcolors.OKCYAN + text + bcolors.ENDC)
    if color == "blue":
        return print(bcolors.OKBLUE + text + bcolors.ENDC)

line = f"{bcolors.OKCYAN}It will wish you on every start up{bcolors.ENDC}"
c_print("cyan", line)

Image showing the color in cmd

Simas Joneliunas
  • 2,890
  • 20
  • 28
  • 35
0

Here is a simple function I find useful to print in color. You do not need to make any imports and you do not have to remember complex ANSI codes. The function uses standard RGB tuples to define the foreground and background color.You can find a RGB color picker at https://www.google.com/search?q=rgb+color+picker&oq=rgb+color+picker&aqs=chrome..69i57j0l7.5967j0j8&sourceid=chrome&ie=UTF-8

def print_in_color(txt_msg,fore_tupple,back_tupple,):
    #prints the text_msg in the foreground color specified by fore_tupple with the background specified by back_tupple 
    #text_msg is the text, fore_tupple is foregroud color tupple (r,g,b), back_tupple is background tupple (r,g,b)
    rf,gf,bf=fore_tupple
    rb,gb,bb=back_tupple
    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))



Gerry P
  • 7,662
  • 3
  • 10
  • 20
  • Your suggested code does the same that already fails for the OP: sending ANSI escape codes to the terminal. Why would your code work for the OP? The accepted answer `colorama` does something entirely else: "Colorama makes this work on Windows, too, by wrapping stdout, stripping ANSI sequences it finds (which would appear as gobbledygook in the output), and converting them into the appropriate win32 calls .." (https://pypi.org/project/colorama/) – Jongware Feb 29 '20 at 17:55
  • Works on windows for me – Gerry P Mar 01 '20 at 06:26
  • Sorry but it depends on the kind of Windows (and its setup) that you have. The `colorama` solution circumvents this. – Jongware Mar 01 '20 at 12:45
  • Thanks for the info. I have not had that happen so I was not aware it was a problem. – Gerry P Mar 02 '20 at 04:11
  • for some reason termcolor has stopped working on my mac and this really helps, thanks! – Jcc.Sanabria Mar 30 '23 at 15:44
0

On modern Windows systems console host window should have mode ENABLE_VIRTUAL_TERMINAL_PROCESSING to correctly process ANSI color sequences.

No external dependencies, pure WinAPI (via ctypes):

def enable_vt_processing():
   import ctypes
   STD_OUTPUT_HANDLE = -11
   handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
   mode = ctypes.c_ulong()
   ok = ctypes.windll.kernel32.GetConsoleMode(handle, ctypes.byref(mode))
   assert ok
   ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
   ok = ctypes.windll.kernel32.SetConsoleMode(handle, ctypes.c_ulong(mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
   assert ok
umi
  • 3,782
  • 2
  • 15
  • 12
0

Add this to make termcolor work in Windows as well:

import colorama
colorama.init()

All of the questions and answers found on StackOverflow appear to be geared specifically towards Windows, but I do want to add that applications made for Linux may want to do this too. If you ever need to pipe the output of your program into a new file from the Linux command line (e.g., python3 myprogram.py > output.txt), you may see the strange control characters in that file! This is often undesirable, especially in log files that system admins are making use of. The above code snippet fixes this issue for me on Ubuntu.

Justin
  • 1
  • 2
0

This works for both linux and windows, if the screen is cleared first.

import os

def clr():
    _ = os.system("cls" if os.name == "nt" else "clear")


clr()
for i in range(0, 16):
    for j in range(0, 16):
        color_code = str(i * 16 + j)
        print("\033[38;5;" + color_code + "m" + color_code.rjust(4), end='')
    print("\033[0m")
mike
  • 1
  • 1