2016-06-28 50 views
1

我是新来的蟒蛇(大约一周或更少),我使用python 2.7。如何使用python制作颜色输出?

我正在写一个程序来检查IP验证和类,我想在颜色的输出,所以它会更可读的终端给用户。

我已经尝试过这样的:

# to make the text purple for example. 
print '\033[95m' + "This is a purple output" 
# if i'm writing another simple print after the first one it will be purple too 
print "Example" # now this statement purple too 

但是当我使用这个例子中,输出后的第一个印刷方法变紫了。

感谢所有尝试的人。

+0

你可以这样做:print'\ 033 [95m'+“这是一个紫色的输出”+'\ 033'0' –

+0

ohh我没看到那个帖子。对不起 – shemesh

回答

2

通过打印换码\033[0m,您可以重置颜色:

>>> print '\033[95m' + "This is a purple output" + '\033[0m' 
This is a purple output 

或者,你可以使用colorama package

>>> from colorama import Fore 
>>> print Fore.LIGHTMAGENTA_EX + "This is a purple output" + Fore.RESET 
This is a purple output 
+0

谢谢,但我需要更高效的更好的方式。 – shemesh

+0

@shemesh,你如何定义高效? – falsetru

+0

我认为'\ 033 [95m'不是必要的,我的意思是说,当你阅读代码时它看起来不太好。我可以使用颜色的所有值的类吗? – shemesh

1

嗯,我想这是我能想到的最好的办法。

class FontColors: 
    def __init__(self): 
     self.PURP = '\033[95m' 
     self.LIGHTBLUE = '\033[94m' 
     self.ENDC = '\033[0m' 
     self.UNDERLINE = '\033[4m' 
     self.LIGHTYELL = '\033[92m' 
     self.BYELL = '\033[93m' 
     self.FRED = '\033[91m' 
     self.BOLD = '\033[1m' 

color = FontColors() 

# you can try like this - **the color.ENDC meant to make the output normal again.** 
print "{0}This is a Purple output{1}".format(color.PURP, color.ENDC) 
# or like this 
print color.BYELL + "This is a Yellow output" + color.ENDC 

谢谢@falsetru帮助我解决这个问题。

+0

你不需要自己定义它们。检查我更新的答案。 – falsetru

+0

得到它的人谢谢。我会投票给你,但我还不能。 – shemesh