如何使用python输出颜色?
我是python新手(大约一周或更少),我正在使用python 2.7 我正在编写一个程序来检查ip验证和类,我想用彩色输出,这样用户在终端上更容易阅读 我已经试过了:如何使用python输出颜色?,python,python-2.7,unicode,terminal,Python,Python 2.7,Unicode,Terminal,我是python新手(大约一周或更少),我正在使用python 2.7 我正在编写一个程序来检查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 p
# 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
但是当我使用这个例子时,第一个print方法之后的输出也变成紫色
感谢所有尝试的人。通过打印转义码
\033[0m
,您可以重置颜色:
>>> print '\033[95m' + "This is a purple output" + '\033[0m'
This is a purple output
或者,您可以使用:
我想这是我能想到的最好的方法
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帮我解决这个问题。谢谢,但我需要一个更好的方法来提高效率。@shemesh,你如何定义效率?我想这个“\033”[95m'不是必需的,我的意思是,当你阅读代码时,它看起来不太好。我可以将类与所有颜色值一起使用吗?@shemesh,我使用第三方软件包添加了一个替代解决方案
colorama
。请查看。谢谢你的帮助,请查看我的解决方案。你不需要自己定义它们。请查看我的最新答案。明白了,谢谢。我会投票支持你,但我还不能。你可以这样做:打印“\033[95m'+”这是紫色输出“+”\033[0m'ohh我没有看到那篇帖子。对不起
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