ANSI Terminal Color Formatting
Termcolor is a Python library that provides ANSI color formatting for output in the terminal. It supports 16 colors, 256 colors, and 24-bit true color modes, along with various text attributes like bold, underline, and italic. It is actively maintained with frequent updates, currently at version 3.3.0.
Warnings
- breaking Termcolor has incrementally dropped support for older Python versions. Version 3.2.0 dropped support for Python 3.9, version 2.5.0 dropped Python 3.8, and version 2.4.0 dropped Python 3.7. The current minimum required Python version is 3.10.
- gotcha The handling of `FORCE_COLOR`, `NO_COLOR`, and `ANSI_COLORS_DISABLED` environment variables changed in version 3.0.0. Prior to 3.0.0, empty string values for these variables might have been interpreted differently. As of 3.0.0, these variables (and `no_color`/`force_color` function parameters) are only applied when present and contain a non-empty string.
- gotcha New text attributes and color modes were introduced in recent versions. The `italic` attribute was added in 3.3.0. True color (RGB tuple) support was added in version 3.1.0. Attempting to use these features with older `termcolor` versions will result in errors or lack of intended formatting.
Install
-
pip install termcolor
Imports
- colored
from termcolor import colored
- cprint
from termcolor import cprint
Quickstart
import sys
from termcolor import colored, cprint
import os
# Basic colored text
print(colored("Hello, World!", "red"))
# Colored text with background and attributes
cprint("Hello, colorful world!", "green", "on_yellow", attrs=["bold", "underline"])
# True color (RGB) example (requires a compatible terminal and termcolor >= 3.1.0)
# You can also specify 0-255 RGB ints via a tuple for color and on_color
if os.environ.get('FORCE_COLOR', '0') == '1': # Check for forced color for consistent demo
cprint("True color text!", (100, 150, 250), (50, 60, 70), attrs=["italic"])
else:
print(colored("Italic attribute and true color (RGB) requires termcolor >= 3.3.0 and >= 3.1.0 respectively, and a compatible terminal.", "white", attrs=["dark"]))
# Print to stderr
cprint("This is an error message.", "red", attrs=["reverse"], file=sys.stderr)