Skip to content

Instantly share code, notes, and snippets.

@Benature
Last active October 28, 2024 15:39
Show Gist options
  • Save Benature/efb344d336b44c61b7a8cc13e73f3fe5 to your computer and use it in GitHub Desktop.
Save Benature/efb344d336b44c61b7a8cc13e73f3fe5 to your computer and use it in GitHub Desktop.
python colorful print
from enum import Enum
from typing import Optional, Union, Literal
class Color(Enum):
gray = "30"
red = "31"
green = "32"
yellow = "33"
blue = "34"
purple = "35"
cyan = "36"
white = "37"
class Style(Enum):
default = "0"
bright = "1"
faded = "2"
italic = "3"
underline = "4"
negative = "7"
none = "8"
class Background(Enum):
red = "41"
green = "42"
yellow = "43"
blue = "44"
purple = "45"
cyan = "46"
gray = "47"
none = "48"
def get_color_format(color: Union[Optional[Color], Literal["gray", "red", "green", "yellow", "blue",
"purple", "cyan", "white"]] = None,
style: Union[Optional[Style],
Literal["default", "bright", "faded", "italic", "underline",
"negative", "none"]] = Style.default,
background: Union[Optional[Background],
Literal["red", "green", "yellow", "blue", "purple", "cyan",
"gray", "none"]] = None,
text: str = None) -> str:
"""Get color format string
Args:
color (Union[Optional[Color], Literal["gray", "red", "green", "yellow", "blue", "purple", "cyan", "white"]], optional): color. Defaults to None.
style (Union[Optional[Style], Literal["default", "bright", "faded", "italic", "underline", "negative", "none"]], optional): Style. Defaults to Style.default.
background (Union[Optional[Background], Literal["red", "green", "yellow", "blue", "purple", "cyan", "gray", "none"]], optional): Background color. Defaults to None.
text (str, optional): Text to be formatted. Defaults to None.
Raises:
ValueError: Invalid color, style or background.
Returns:
str: Color format string
"""
if color is None and style is None and background is None:
return "{}"
args = dict(c=(color, Color), s=(style, Style), b=(background, Background))
for key, (value, cls) in args.items():
if isinstance(value, str):
if value in cls.__members__:
args[key] = (cls[value], cls)
else:
raise ValueError(f"Invalid {key}: {value}")
color, style, background = [value for _, (value, _) in args.items()]
prefix = f"\033[{style.value}"
if color is not None:
prefix += f";{color.value}"
if background is not None:
prefix += f";{background.value}"
prefix += "m"
suffix = "\033[0m"
pattern = prefix + "{}" + suffix
if text is None:
return pattern
else:
return pattern.format(text)
def cprint(*values,
color: Union[Optional[Color], Literal["gray", "red", "green", "yellow", "blue", "purple",
"cyan", "white"]] = None,
style: Union[Optional[Style], Literal["default", "bright", "faded", "italic",
"underline", "negative", "none"]] = Style.default,
background: Union[Optional[Background],
Literal["red", "green", "yellow", "blue", "purple", "cyan", "gray",
"none"]] = None,
sep=" ",
end="\n",
file=None,
flush: Literal[False] = False) -> None:
"""Colored print()
Args:
color (Union[Optional[Color], Literal["gray", "red", "green", "yellow", "blue", "purple", "cyan", "white"]], optional): color. Defaults to None.
style (Union[Optional[Style], Literal["default", "bright", "faded", "italic", "underline", "negative", "none"]], optional): Style. Defaults to Style.default.
background (Union[Optional[Background], Literal["red", "green", "yellow", "blue", "purple", "cyan", "gray", "none"]], optional): Background color. Defaults to None.
sep (str, optional): separator, same as in print(). Defaults to " ".
end (str, optional): end charactor, same as in print(). Defaults to "\\n".
file (_type_, optional): same as in print(). Defaults to None.
flush (Literal[False], optional): same as in print(). Defaults to False.
"""
text = sep.join(str(value) for value in values)
format = get_color_format(color, style, background)
print(format.format(text), end=end, file=file, flush=flush)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment