Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does termcolor output control characters instead of colored text in the Windows console?

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.

like image 482
user3170921 Avatar asked Feb 18 '14 15:02

user3170921


3 Answers

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
>>>
like image 182
Joachim Isaksson Avatar answered Oct 11 '22 15:10

Joachim Isaksson


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')
like image 40
Tarun Sethupat Avatar answered Oct 11 '22 16:10

Tarun Sethupat


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

like image 3
Morteza Rahmani Avatar answered Oct 11 '22 14:10

Morteza Rahmani