Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

In màu trên terminal Python với termcolor

Module termcolor cung cấp định dạng màu ANSI cho output terminal.

Cài đặt

pip install termcolor

Sử dụng cơ bản

from termcolor import colored, cprint
import sys

# colored() trả về string có màu
text1 = colored('Hello, Tutorialspoint!', 'blue', attrs=['reverse', 'blink'])
print(text1)

# cprint() in trực tiếp
cprint('Hello, Python!', 'blue', 'on_white')

# Lambda tiện lợi
print_red_on_blue = lambda x: cprint(x, 'red', 'on_blue')
print_red_on_blue('Hello, from Data Science!')
print_red_on_blue('Hello, Python!')

# In loop với màu
for i in range(10):
    cprint(i, 'green', end=' ')

# In ra stderr
cprint("Attention!", 'blue', attrs=['bold'], file=sys.stderr)

Màu hỗ trợ

Text colorgrey, red, green, yellow, blue, magenta, cyan, white
Backgroundon_grey, on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white
Attributesbold, dark, underline, blink, reverse, concealed

Kết quả

In màu trên terminal Python với termcolor

Thay thế không cần cài đặt (ANSI escape codes)

class Colors:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    RESET = '\033[0m'

print(f"{Colors.RED}Error!{Colors.RESET}")
print(f"{Colors.GREEN}Success{Colors.RESET}")

Lưu ý

  • Windows CMD cũ không hỗ trợ ANSI → dùng colorama (colorama.init())
  • Windows 10+ Terminal/PowerShell hỗ trợ sẵn
  • Không lạm dụng màu trong log file (khó đọc khi grep)