crayons
Crayons is a simple Python module that provides colored strings for terminal usage, automatically wrapping a given string in both the foreground color and resetting to the original state after the string is complete. It aims to simplify terminal coloring by managing ANSI escape codes for the user. The current version is 0.4.0, released in August 2020, indicating a stable but less frequently updated library.
Warnings
- breaking The `clean` function was completely rewritten in v0.3.0. Previously, it might have stripped all characters, but now it specifically removes ANSI escape codes.
- gotcha As of v0.4.0, `crayons` explicitly checks if `sys.stdout` has an `isatty` attribute and if it's `True` before displaying colors. If using a custom stdout object without `isatty` or if `isatty` is `False` (e.g., in a piped environment), colors might not display.
- gotcha Prior to v0.3.1, passing non-string parameters directly to `crayons` functions could lead to unexpected behavior (e.g., issues with `len`).
Install
-
pip install crayons
Imports
- crayons
import crayons
Quickstart
import crayons
import os
# Basic color usage
print(crayons.red("This text is red."))
print(crayons.green("This text is green and bold.", bold=True))
print(crayons.blue("This is blue text."))
# Using 'always=True' to force color even when not in a TTY
print(crayons.yellow("This warning should always be yellow.", always=True))
# Demonstrating the clean function
colored_text = crayons.magenta("Hello, colorful world!")
print(f"Original: {colored_text}")
print(f"Cleaned: {crayons.clean(colored_text)}")
# Force color using environment variable (useful for CI/CD or non-TTY environments)
# os.environ['CLINT_FORCE_COLOR'] = '1'
# print(crayons.cyan("This should be cyan even if not in a TTY due to env var."))
# del os.environ['CLINT_FORCE_COLOR'] # Clean up environment variable for subsequent tests