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.
pip install crayonsVerified import paths — ran on the pinned version, not inferred.
Import the `crayons` library and call color functions (e.g., `crayons.red()`) with your string. You can pass `bold=True` for bold text or `always=True` to force color output even when not in a TTY. The `clean()` function removes ANSI escape codes from a colored string.
If you relied on `crayons.clean()` to strip all non-alphanumeric characters, its behavior changed. Test your code with v0.3.0+ to ensure the new behavior (ANSI code stripping only) is what you expect. If not, implement your own string cleaning logic.
To force color output regardless of the TTY status, set the `CLINT_FORCE_COLOR` environment variable to any non-empty value (e.g., `export CLINT_FORCE_COLOR=1` or `os.environ['CLINT_FORCE_COLOR'] = '1'` in Python code). Alternatively, use `always=True` on individual color calls.
Ensure all inputs to `crayons` color functions are strings. Version 0.3.1 and later explicitly convert incoming parameters to strings, but it's good practice to provide strings yourself.
Ensure your Python script is run directly in an interactive terminal. If you explicitly want colors when piping or redirecting output, you might need to use `crayons.always = True` (though this is not explicitly documented for version 0.4.0, it's a common pattern in similar libraries or earlier/later versions of `crayons` for forcing output). For version 0.4.0, the documentation states 'If the current process is not in a TTY (e.g. being piped), no colors will be displayed', implying this behavior is by design and not directly overridable by a simple flag in this specific version.
Use one of the supported color attributes, e.g., `crayons.magenta('Hello, World!')`.The color attributes in `crayons` are directly callable. Ensure you are calling the color function with the string argument, e.g., `print(crayons.red('This is red'))`. If you store the colored string, it becomes a `ColoredString` instance and is no longer callable as a function, e.g., `my_red_text = crayons.red('Hello'); print(my_red_text)` is correct, but `print(my_red_text('World'))` would cause this error.Install the package using pip: `pip install crayons`