Cross-platform colored terminal text output with ANSI sequence support for Windows
npx @tessl/cli install tessl/pypi-colorama@0.4.0A Python library that enables cross-platform colored terminal text output by making ANSI escape character sequences work on MS Windows. On Unix and Mac platforms, colorama does nothing and allows native ANSI support to work unchanged, providing a simple cross-platform API for printing colored terminal text.
pip install coloramaimport colorama
from colorama import init, just_fix_windows_console, deinit, reinit, colorama_text
from colorama import Fore, Back, Style, Cursor, AnsiToWin32
from colorama import code_to_chars, set_title, clear_screen, clear_lineAlternative for Windows-only fix:
from colorama import just_fix_windows_console
just_fix_windows_console()from colorama import init, Fore, Back, Style
# Initialize colorama
init()
# Simple colored text
print(Fore.RED + 'Hello World!' + Style.RESET_ALL)
print(Back.GREEN + 'Green background' + Style.RESET_ALL)
print(Style.BRIGHT + 'Bright text' + Style.RESET_ALL)
# Combining colors and styles
print(Fore.YELLOW + Back.BLUE + Style.BRIGHT + 'Yellow on blue, bright' + Style.RESET_ALL)
# Context manager usage
from colorama import colorama_text
with colorama_text():
print(Fore.CYAN + 'This will be cyan')
# Automatically deinitializedConfigure colorama behavior and enable cross-platform ANSI support.
def init(autoreset=False, convert=None, strip=None, wrap=True):
"""
Initialize colorama.
Args:
autoreset (bool): Auto-reset colors after each print. Default: False
convert (bool|None): Convert ANSI sequences to Win32 calls. Default: None (auto-detect)
strip (bool|None): Strip ANSI sequences from output. Default: None (auto-detect)
wrap (bool): Wrap stdout/stderr streams. Default: True
Returns:
None
Raises:
ValueError: If wrap=False conflicts with any other arg=True
"""
def deinit():
"""
De-initialize colorama, restore original stdout/stderr streams.
Returns:
None
"""
def reinit():
"""
Re-initialize colorama with previous settings.
Returns:
None
"""
def just_fix_windows_console():
"""
Minimal fix for Windows console ANSI support.
On newer Windows versions, enables native ANSI support.
On older versions, wraps streams only if needed.
Does nothing on non-Windows platforms.
Returns:
None
"""
def colorama_text(*args, **kwargs):
"""
Context manager for temporary colorama usage.
Args:
*args, **kwargs: Same arguments as init()
Returns:
Context manager that calls init() on enter and deinit() on exit
"""Set text foreground colors using ANSI escape sequences.
class Fore:
"""Foreground color constants."""
BLACK: str # Black text
RED: str # Red text
GREEN: str # Green text
YELLOW: str # Yellow text
BLUE: str # Blue text
MAGENTA: str # Magenta text
CYAN: str # Cyan text
WHITE: str # White text
RESET: str # Reset to default foreground color
# Extended colors (may not be supported on all terminals)
LIGHTBLACK_EX: str # Light black text
LIGHTRED_EX: str # Light red text
LIGHTGREEN_EX: str # Light green text
LIGHTYELLOW_EX: str # Light yellow text
LIGHTBLUE_EX: str # Light blue text
LIGHTMAGENTA_EX: str # Light magenta text
LIGHTCYAN_EX: str # Light cyan text
LIGHTWHITE_EX: str # Light white textSet text background colors using ANSI escape sequences.
class Back:
"""Background color constants."""
BLACK: str # Black background
RED: str # Red background
GREEN: str # Green background
YELLOW: str # Yellow background
BLUE: str # Blue background
MAGENTA: str # Magenta background
CYAN: str # Cyan background
WHITE: str # White background
RESET: str # Reset to default background color
# Extended colors (may not be supported on all terminals)
LIGHTBLACK_EX: str # Light black background
LIGHTRED_EX: str # Light red background
LIGHTGREEN_EX: str # Light green background
LIGHTYELLOW_EX: str # Light yellow background
LIGHTBLUE_EX: str # Light blue background
LIGHTMAGENTA_EX: str # Light magenta background
LIGHTCYAN_EX: str # Light cyan background
LIGHTWHITE_EX: str # Light white backgroundControl text brightness and styling with ANSI escape sequences.
class Style:
"""Text style constants."""
BRIGHT: str # Bright/bold text
DIM: str # Dim text (may appear same as normal on Windows)
NORMAL: str # Normal brightness text
RESET_ALL: str # Reset all formatting (colors and styles)Control cursor movement and positioning in the terminal.
class Cursor:
"""Cursor positioning methods."""
def UP(n=1):
"""
Move cursor up n lines.
Args:
n (int): Number of lines to move up. Default: 1
Returns:
str: ANSI escape sequence for cursor movement
"""
def DOWN(n=1):
"""
Move cursor down n lines.
Args:
n (int): Number of lines to move down. Default: 1
Returns:
str: ANSI escape sequence for cursor movement
"""
def FORWARD(n=1):
"""
Move cursor forward n columns.
Args:
n (int): Number of columns to move forward. Default: 1
Returns:
str: ANSI escape sequence for cursor movement
"""
def BACK(n=1):
"""
Move cursor back n columns.
Args:
n (int): Number of columns to move back. Default: 1
Returns:
str: ANSI escape sequence for cursor movement
"""
def POS(x=1, y=1):
"""
Set cursor position to specific coordinates.
Args:
x (int): Column position (1-based). Default: 1
y (int): Row position (1-based). Default: 1
Returns:
str: ANSI escape sequence for cursor positioning
"""Low-level functions for generating ANSI escape sequences and terminal control.
def code_to_chars(code):
"""
Convert an ANSI code number to ANSI escape sequence string.
Args:
code (int): ANSI code number
Returns:
str: ANSI escape sequence (e.g., '\033[31m' for red foreground)
"""
def set_title(title):
"""
Generate ANSI sequence to set terminal window title.
Args:
title (str): Terminal title to set
Returns:
str: ANSI escape sequence for setting title
"""
def clear_screen(mode=2):
"""
Generate ANSI sequence to clear terminal screen.
Args:
mode (int): Clear mode - 0: cursor to end, 1: start to cursor, 2: entire screen. Default: 2
Returns:
str: ANSI escape sequence for screen clearing
"""
def clear_line(mode=2):
"""
Generate ANSI sequence to clear terminal line.
Args:
mode (int): Clear mode - 0: cursor to end, 1: start to cursor, 2: entire line. Default: 2
Returns:
str: ANSI escape sequence for line clearing
"""For advanced use cases requiring direct access to Windows conversion functionality.
class AnsiToWin32:
"""
ANSI to Win32 conversion wrapper for Windows terminals.
Wraps a stream (typically stdout/stderr) and converts ANSI escape
sequences to appropriate Win32 console API calls on Windows.
"""
def __init__(wrapped, convert=None, strip=None, autoreset=False):
"""
Initialize ANSI to Win32 converter.
Args:
wrapped: The stream to wrap (e.g., sys.stdout)
convert (bool|None): Convert ANSI to Win32 calls. Default: None (auto-detect)
strip (bool|None): Strip ANSI sequences. Default: None (auto-detect)
autoreset (bool): Auto-reset after each write. Default: False
"""
# Properties
stream: object # The wrapped stream proxy
wrapped: object # The original stream
convert: bool # Whether to convert ANSI sequences to Win32 calls
strip: bool # Whether to strip ANSI sequences from output
autoreset: bool # Whether to auto-reset colors after each write
on_stderr: bool # Whether this wraps stderr (vs stdout)
def write(text):
"""
Write text to wrapped stream with ANSI conversion.
Args:
text (str): Text to write
Returns:
None
"""
def flush():
"""
Flush the wrapped stream.
Returns:
None
"""
def reset_all():
"""
Reset all terminal formatting.
Returns:
None
"""
def should_wrap():
"""
Check if stream wrapping is actually needed.
Returns:
bool: True if wrapping provides functionality, False otherwise
"""from colorama import init, Fore, Back, Style
init()
# Basic colors
print(Fore.RED + "Error: Something went wrong" + Style.RESET_ALL)
print(Fore.GREEN + "Success: Operation completed" + Style.RESET_ALL)
print(Fore.YELLOW + "Warning: Please check this" + Style.RESET_ALL)
# Background colors
print(Back.BLUE + Fore.WHITE + "White text on blue background" + Style.RESET_ALL)
# Bright/dim styles
print(Style.BRIGHT + Fore.RED + "Bright red text" + Style.RESET_ALL)
print(Style.DIM + "Dim text" + Style.RESET_ALL)from colorama import init, Fore, Back, Style
# Enable auto-reset - colors reset after each print
init(autoreset=True)
print(Fore.RED + "This will be red")
print("This will be normal color") # No need for Style.RESET_ALL
print(Back.GREEN + "Green background")
print("Normal background again")from colorama import colorama_text, Fore, Style
# Temporary colorama initialization
with colorama_text(autoreset=True):
print(Fore.CYAN + "Cyan text")
print(Style.BRIGHT + "Bright text")
# Colorama automatically deinitialized here
print("Normal text - colorama not active")from colorama import init, Cursor, Fore
init()
print("Line 1")
print("Line 2")
print("Line 3")
# Move cursor up and overwrite
print(Cursor.UP(2) + Cursor.FORWARD(5) + Fore.RED + "CHANGED" + Fore.RESET)
# Set specific position
print(Cursor.POS(10, 1) + "At column 10, row 1")from colorama import init, code_to_chars, set_title, clear_screen, clear_line, Fore
init()
# Manual ANSI code generation
red_code = code_to_chars(31) # '\033[31m'
print(red_code + "Manual red text" + code_to_chars(0)) # Reset with code 0
# Set terminal title
title_sequence = set_title("My Python Application")
print(title_sequence, end='') # Set title without newline
# Clear screen
print("Some text that will be cleared...")
print(clear_screen(), end='') # Clear entire screen
# Clear line
print("This line will be partially cleared", end='')
print(clear_line(0), end='') # Clear from cursor to end of line
print("New text on same line")from colorama import just_fix_windows_console
# Just enable Windows ANSI support without other colorama features
just_fix_windows_console()
# Now ANSI sequences work on Windows
print('\033[31mRed text\033[0m') # Raw ANSI sequences
print('\033[32mGreen text\033[0m')# All color and style constants are strings containing ANSI escape sequences
Fore.RED: str = '\033[31m'
Back.BLUE: str = '\033[44m'
Style.BRIGHT: str = '\033[1m'
Style.RESET_ALL: str = '\033[0m'
# Cursor methods return ANSI escape sequence strings
Cursor.UP(2): str = '\033[2A'
Cursor.POS(5, 3): str = '\033[3;5H'
# Utility functions return ANSI escape sequence strings
code_to_chars(31): str = '\033[31m'
set_title("Title"): str = '\033]2;Title\a'
clear_screen(): str = '\033[2J'
clear_line(): str = '\033[2K'
# Initialization functions return None
init(): None
deinit(): None
just_fix_windows_console(): None# Access via colorama module import
import colorama
colorama.__version__: str = '0.4.6' # Package version
# Or access directly
from colorama import __version__
__version__: str = '0.4.6'The library handles errors gracefully:
init() raises ValueError if wrap=False conflicts with other True arguments