插件窝 干货文章 Python终端彩色输出:如何优雅地实现?

Python终端彩色输出:如何优雅地实现?

转义 颜色 colorama 使用 809    来源:    2025-03-13

在Python终端中实现彩色输出可以通过使用ANSI转义序列来实现。ANSI转义序列是一种用于控制终端文本颜色、背景颜色、样式等的特殊字符序列。为了更优雅地实现彩色输出,可以使用第三方库如 coloramatermcolor,它们提供了更高级的接口来简化彩色输出的实现。

方法1:使用ANSI转义序列

ANSI转义序列以 \033[ 开头,后面跟着颜色代码和样式代码,最后以 m 结尾。

# 定义颜色代码
class Colors:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    MAGENTA = '\033[95m'
    CYAN = '\033[96m'
    WHITE = '\033[97m'
    RESET = '\033[0m'  # 重置颜色

# 使用颜色
print(f"{Colors.RED}This is red text{Colors.RESET}")
print(f"{Colors.GREEN}This is green text{Colors.RESET}")
print(f"{Colors.BLUE}This is blue text{Colors.RESET}")

方法2:使用 colorama

colorama 是一个跨平台的库,可以自动处理不同操作系统下的ANSI转义序列兼容性问题。

  1. 安装 colorama

    pip install colorama
    
  2. 使用 colorama

    from colorama import Fore, Back, Style, init
    
    # 初始化colorama
    init()
    
    # 使用颜色
    print(Fore.RED + 'This is red text')
    print(Fore.GREEN + 'This is green text')
    print(Fore.BLUE + 'This is blue text')
    
    # 重置颜色
    print(Style.RESET_ALL + 'This is normal text')
    

方法3:使用 termcolor

termcolor 是另一个用于终端彩色输出的库,提供了更高级的接口。

  1. 安装 termcolor

    pip install termcolor
    
  2. 使用 termcolor

    from termcolor import colored
    
    # 使用颜色
    print(colored('This is red text', 'red'))
    print(colored('This is green text', 'green'))
    print(colored('This is blue text', 'blue'))
    
    # 还可以指定背景颜色和文本样式
    print(colored('This is bold red text on a white background', 'red', 'on_white', ['bold']))
    

总结

  • ANSI转义序列:适合简单的彩色输出,但需要手动处理颜色代码。
  • colorama:跨平台兼容性好,适合需要跨平台支持的场景。
  • termcolor:提供了更高级的接口,适合需要更多样式控制的场景。

根据你的需求选择合适的方法来实现Python终端的彩色输出。