使用Python如何实现彩色输出?

3

我是一个新手,刚接触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
print "Example" # now this statement purple too

但是当我使用这个例子时,第一个print方法后的输出也变成了紫色。 感谢所有尝试过的人。

你可以这样做:print '\033[95m' + "这是紫色输出" + '\033[0m' - R Chaudhary
哦,我没有看到那篇帖子。抱歉。 - shemesh
2个回答

3
通过打印转义码 \033[0m,您可以重置颜色:
>>> print '\033[95m' + "This is a purple output" + '\033[0m'
This is a purple output

或者,您可以使用colorama

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

谢谢你,但我需要一种更好、更高效的方法。 - shemesh
@shemesh,你如何定义高效? - falsetru
我认为这个 '\033[95m' 不是必要的,我的意思是当你阅读代码时它看起来并不好。我能否使用包含所有颜色值的类? - shemesh
@shemesh,我添加了一种使用第三方包colorama的替代解决方案。看看吧。 - falsetru
谢谢你,朋友。请看看我的解决方案,感谢你的帮助。 - shemesh
@shemesh,正如我在您的解决方案中评论的那样,如果您使用colorama包,则无需定义类。 - falsetru

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 帮助我解决这个问题。


你不需要自己定义它们。请查看我的更新答案。 - falsetru
明白了,谢谢你。我会给你投票的,但我现在还不能。 - shemesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接