您的位置:宽带测速网 > 编程知识 > python重定向输出文字如何着色

python重定向输出文字如何着色

2025-06-22 18:07来源:互联网 [ ]

可以使用ANSI转义码来在终端中着色输出文字。以下是使用ANSI转义码在Python中实现文字着色的示例代码:

# ANSI转义码颜色代码class colors:HEADER = '\033[95m'OKBLUE = '\033[94m'OKGREEN = '\033[92m'WARNING = '\033[93m'FAIL = '\033[91m'ENDC = '\033[0m'# 输出带颜色的文字print(colors.OKGREEN + "This text is green." + colors.ENDC)print(colors.WARNING + "This text is yellow." + colors.ENDC)print(colors.FAIL + "This text is red." + colors.ENDC)

在上面的示例中,colors类定义了不同颜色的ANSI转义码。你可以使用colors.OKGREENcolors.WARNINGcolors.FAIL等颜色代码来给输出的文字着色。记得在需要恢复默认颜色之前使用colors.ENDC来结束颜色设置。