Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colorama for Python, Not returning colored print lines on Windows

Tags:

I've installed colorama for python. I've imported the module as follows:

import colorama from colorama import init init() from colorama import Fore, Back, Style  print Fore.RED + "My Text is Red" 

and it returns the ANSI charaters....

esc[31mMy Text is Red 

This isn`t what I expected. Am I doing something wrong.

Thanks.

like image 564
Mike Avatar asked Mar 24 '12 03:03

Mike


People also ask

Does Colorama work in Windows?

On Windows, Colorama works by replacing sys. stdout and sys. stderr with proxy objects, which override the . write() method to do their work.

How do I fix Colorama in Python?

The Python "ModuleNotFoundError: No module named 'colorama'" occurs when we forget to install the colorama module before importing it or install it in an incorrect environment. To solve the error, install the module by running the pip install colorama command.

How do you change the color of text in Python Colorama?

Changing text color In colorama, the font color or the text color is referred to as Fore(stands for foreground). To change the font color, start by importing the module. Then, in the print statement, mention the color you want to use.


2 Answers

I had this same issue on Windows 7 x64, I finally got the colors working without having to install anything new just by adding the argument convert=True to the init call.

from colorama import init, Fore, Back, Style  init(convert=True)  print(Fore.RED + 'some red text') 
like image 155
hrbdg Avatar answered Sep 16 '22 17:09

hrbdg


I've never had success getting colors working in Windows cmd.exe without patching it with Ansicon. After patching, ANSI color codes will work without needing to use something like colorama (which didn't work for me either).

To patch cmd.exe with Ansicon, do the following:

  1. Download Ansicon from https://github.com/adoxa/ansicon/downloads and unzip it into a directory with no spaces
  2. Use a cmd prompt and navigate to where you unzipped it.
  3. CD into the x64 directory (unless you have a 32bit machine, then use the x86 one)
  4. Type ansicon.exe –i
  5. Open a new cmd prompt

via: https://stackoverflow.com/a/4749307/191902

Also, if you have an NVidia graphics card, you might need to set the environment variable "ANSICON_EXC" to "nvd3d9wrap.dll".

like image 23
Sean Lynch Avatar answered Sep 17 '22 17:09

Sean Lynch