【Python】控制台彩色输出工具类

✨Python控制台彩色输出工具类封装

之前介绍了 Logging不同颜色日志输出的

【Python】Logging模块简介 & 开启不同颜色日志输出 - 双份浓缩馥芮白 - 博客园 (cnblogs.com)

由于有的项目中本来就封装了日志工具类(例如yolov5)

或者是某些方法内部会修改logger.handlers(例如torch.hub.load()

可能导致上述博客中的封装混乱或者失效


因此本文介绍Python已经封装好的控制台彩色输出工具类

新建colorprinter.py

代码如下

from colorama import Fore, Back, Style


def print_red(text):
    color_text = Fore.RED + str(text) + Style.RESET_ALL
    print(color_text)


def print_green(text):
    color_text = Fore.GREEN + str(text) + Style.RESET_ALL
    print(color_text)


def print_yellow(text):
    color_text = Fore.YELLOW + str(text) + Style.RESET_ALL
    print(color_text)


def print_blue(text):
    color_text = Fore.BLUE + str(text) + Style.RESET_ALL
    print(color_text)


def print_magenta(text):
    color_text = Fore.MAGENTA + str(text) + Style.RESET_ALL
    print(color_text)


def print_cyan(text):
    color_text = Fore.CYAN + str(text) + Style.RESET_ALL
    print(color_text)


def print_white(text):
    color_text = Fore.WHITE + str(text) + Style.RESET_ALL
    print(color_text)


def print_black_bg(text):
    color_text = Back.BLACK + str(text) + Style.RESET_ALL
    print(color_text)


def print_white_bg(text):
    color_text = Back.WHITE + str(text) + Style.RESET_ALL
    print(color_text)

使用时直接调用即可

from colorprinter import *

print_red("This is a red text.")
print_green("This is a green text.")
reset_style()

⭐转载请注明出处

本文作者:双份浓缩馥芮白

原文链接:https://www.cnblogs.com/Flat-White/p/17255977.html

版权所有,如需转载请注明出处。

posted @ 2023-03-25 23:45  双份浓缩馥芮白  阅读(79)  评论(0编辑  收藏  举报