Python ANSI Colors - Terminal Color Output with Print
Print colored text in Python using ANSI escape codes. Covers raw escape sequences, the colorama library, and rich library for cross-platform terminal color support.
Language Examples
Detailed Explanation
Colored Terminal Output in Python
Python supports ANSI escape sequences natively in print statements. This guide covers both raw escape codes and popular library approaches.
Raw ANSI Escape Sequences
# Basic colors
print("\033[31mRed text\033[0m")
print("\033[1;32mBold green\033[0m")
print("\033[4;34mUnderlined blue\033[0m")
# 256 colors
print("\033[38;5;208mOrange text\033[0m")
# True color
print("\033[38;2;255;165;0mTrue orange\033[0m")
Color Constants Class
class Color:
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
BOLD = "\033[1m"
DIM = "\033[2m"
UNDERLINE = "\033[4m"
RESET = "\033[0m"
@staticmethod
def rgb(r, g, b):
return f"\033[38;2;{r};{g};{b}m"
@staticmethod
def bg_rgb(r, g, b):
return f"\033[48;2;{r};{g};{b}m"
# Usage
print(f"{Color.RED}Error: File not found{Color.RESET}")
print(f"{Color.BOLD}{Color.GREEN}Success!{Color.RESET}")
print(f"{Color.rgb(255, 165, 0)}Custom orange{Color.RESET}")
Using f-strings with Colors
def colored(text, code):
return f"\033[{code}m{text}\033[0m"
# Semantic helpers
def error(msg): return colored(msg, "1;31")
def success(msg): return colored(msg, "1;32")
def warning(msg): return colored(msg, "1;33")
def info(msg): return colored(msg, "1;36")
print(error("Build failed"))
print(success("All 42 tests passed"))
print(warning("Deprecated API used"))
Windows Compatibility
On Windows, ANSI escape codes require enabling Virtual Terminal Processing:
import os
import sys
# Enable ANSI on Windows 10+
if sys.platform == "win32":
os.system("") # Simple trick to enable ANSI support
# Or use colorama for broader Windows support
# pip install colorama
# from colorama import init
# init()
Conditional Colors
import sys
USE_COLOR = sys.stdout.isatty() and os.environ.get("NO_COLOR") is None
def maybe_color(text, code):
if USE_COLOR:
return f"\033[{code}m{text}\033[0m"
return text
Use Case
Python developers use colored terminal output in CLI tools built with argparse or click, test frameworks like pytest (green for pass, red for fail), data processing scripts that show progress, web scraping tools that display status, and DevOps automation scripts. The colorama and rich libraries provide higher-level abstractions for production applications.