get_ansi_color_code¶
- pyhelpers.ops.get_ansi_color_code(colors, show_valid_colors=False, concatenated=True)[source]¶
Returns the ANSI escape code(s) for the given color name(s) and/or style(s).
The function handles both single attribute requests and compound sequences (e.g.
['red', 'blue']) by concatenating the codes into a single escape sequence string when appropriate.- Parameters:
colors (str | list[str] | tuple[str]) – A single color/style name (str) or a sequence of names (e.g.
'red','bold',['red', 'bg_blue']).show_valid_colors (bool) – If
True, returns a tuple containing the final output (string or list) and a set of all valid color/style names.concatenated (bool) – If
True(default), multiple requested codes are concatenated into a single string (e.g.'\u001b[31m\u001b[1m'). IfFalse, a list of individual escape code strings is returned (e.g.['\u001b[31m', '\u001b[1m']).
- Returns:
The ANSI escape code(s). This is a single string if
concatenated=True, a list of strings ifconcatenated=Falseand multiple items were requested, or a tuple ifshow_valid_colors=True.- Return type:
str | list[str] | tuple[Union[str, list[str]], set[str]]
- Raises:
ValueError – If an invalid color or style name is provided.
Examples:
>>> from pyhelpers.ops import get_ansi_color_code >>> get_ansi_color_code('red') # \u001b[31m '\033[31m' >>> get_ansi_color_code(['red', 'blue']) # \u001b[31m\u001b[34m ['\033[31m', '\033[34m'] >>> get_ansi_color_code(['red', 'blue'], concatenated=False) '\033[31m\033[34m' >>> get_ansi_color_code('invalid_color') Traceback (most recent call last): ... ValueError: 'invalid_color' is not a valid color name. >>> get_ansi_color_code('red', show_valid_colors=True) # ('\u001b[31m', ... ('\033[31m', {'bg_black', 'bg_blue', 'bg_bright_black', 'bg_bright_blue', ...