Colorclass
Colorclass is a Python library for creating colorful and worry-free console applications, providing ANSI color text support for Linux, Mac OS X, and Windows. It includes 'auto colors' functionality to adapt to dark/light terminals. The current stable version is 2.2.2, released in December 2021, and it is actively maintained.
Warnings
- gotcha On Windows, ANSI color codes are not enabled by default for older terminals. You must call `Windows.enable()` in your application to properly display colors. Even on modern Windows 10/11, it's recommended for auto-color detection.
- breaking In Python 2.x, `colorclass` string objects subclass `unicode`, whereas in Python 3.x, they subclass `str`. This might lead to compatibility issues if your code explicitly checks types using `isinstance(obj, unicode)` or `isinstance(obj, str)` without considering the Python version.
- gotcha When `colorclass` is used via piped command line (`python -m colorclass`), environment variables like `COLOR_DISABLE=true` or `COLOR_ENABLE=true` can override automatic color detection, forcing colors off or on, respectively.
Install
-
pip install colorclass
Imports
- Color
from colorclass import Color
- Windows
from colorclass import Windows
- list_tags
from colorclass import list_tags
Quickstart
from colorclass import Color, Windows, list_tags
import os
# Enable Windows console support (required for colors on Windows)
# Check if running on CI/CD or in a non-interactive environment
if os.name == 'nt' and os.environ.get('CI') != 'true' and os.isatty(1):
Windows.enable()
# Print a simple colored string
print(Color('{red}This text is red.{/red}'))
# Combine multiple colors and styles
print(Color('{autoblue}{bgwhite}Blue text on white background.{/bgwhite}{/autoblue}'))
# Use auto colors for terminals
print(Color('{autoyellow}This text adapts to terminal background.{/autoyellow}'))
# List available tags
print('\nAvailable tags:')
for tag in sorted(list_tags()):
print(f'- {tag}')