ANSI colors for Python
The `ansicolors` library provides a simple way to add ANSI escape codes for foreground, background, and text styles to strings for terminal output. It supports 8-color, 256-color (xterm), and 24-bit RGB color definitions. The current version is 1.1.8, released in June 2017, and the project appears to be in maintenance mode due to lack of recent updates.
Warnings
- gotcha The PyPI package is named `ansicolors`, but the Python module to import is `colors`. Importing `ansicolors` directly will not work as expected.
- deprecated The library has not seen a release since June 2017. It is likely no longer actively maintained, meaning no new features, bug fixes, or compatibility updates for newer Python versions or terminal standards.
- gotcha Not all ANSI styles (e.g., `blink`, `concealed`) are universally supported across different terminal emulators. Relying on these for critical visual cues can lead to inconsistent user experiences.
- gotcha Advanced color modes (256-color and 24-bit RGB) are not supported by all terminal emulators. Output may not render correctly or fall back to basic 8-color approximations on incompatible terminals.
- gotcha On older Windows consoles (prior to Windows 10's native ANSI support), ANSI escape codes may not render correctly without specific registry modifications (setting `VirtualTerminalLevel` to 1) or using modern terminals like Windows Terminal.
Install
-
pip install ansicolors
Imports
- color
from colors import color
Quickstart
from colors import color
import os
# Basic 8-color
print(color('Hello, ANSI!', fg='green'))
print(color('Warning!', fg='black', bg='yellow', style='bold'))
# Check for color support (common practice)
if os.environ.get('NO_COLOR') is None and os.stdout.isatty():
# 256-color (xterm) example
print("\n256-color palette (if supported):")
for i in range(256):
if i % 16 == 0:
print()
print(color(f'{i:03d}', fg=i), end=' ')
print('\n')
# 24-bit RGB example
print(color('True Color!', fg=(255, 100, 50), style='underline'))
print(color('Deep Blue Background', bg='#00008b', fg='white'))
else:
print("\nTerminal does not support ANSI colors or NO_COLOR is set.")