Python, Colorama, assign color code to variable

3.9k views Asked by At

I have changed the colors of Python console using the following code:

from colorama import init
init()
from colorama import Fore, Back, Style
print(Fore.COLORNAME)

But I have to set COLORNAME myself, like this:
print(Fore.RED)

What I'm trying to do is to make COLORNAME as variable, so that I can change from somewhere else, I wanna make it something like this:

COLORNAME = 'RED'
print(Fore.COLORNAME)

and the test should be printed as RED, but I'm getting this error:
'AnsiCode object has no attribute str'
because this:
COLORNAME = 'RED'
mean I'm assigning a string to the variable COLORNAME.
Any ideas please? Thank you.

Windows 8, 64bit, Python 2.7

1

There are 1 answers

0
famousgarkin On BEST ANSWER

That's correct, the colorama.Fore object doesn't have a COLORNAME attribute. You can use the string value of COLORAMA to get a Fore object attribute using getattr:

COLORNAME = 'RED'
color = getattr(Fore, COLORNAME)
print(color)