From 492a4319ecbda758bca25a6dc7fb7823ca5cba61 Mon Sep 17 00:00:00 2001 From: Sven Augustin Date: Mon, 14 Mar 2022 18:27:49 +0100 Subject: [PATCH] added cprint (simple colored print function) --- slic/utils/__init__.py | 1 + slic/utils/cprint.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 slic/utils/cprint.py diff --git a/slic/utils/__init__.py b/slic/utils/__init__.py index 864fefe2..8ae39979 100644 --- a/slic/utils/__init__.py +++ b/slic/utils/__init__.py @@ -2,6 +2,7 @@ from .utils import * from .argfwd import forwards_to from .channels import load_channels, Channels +from .cprint import cprint from .config import Config from .elog import Elog from .eval import arithmetic_eval diff --git a/slic/utils/cprint.py b/slic/utils/cprint.py new file mode 100644 index 00000000..35a06171 --- /dev/null +++ b/slic/utils/cprint.py @@ -0,0 +1,42 @@ +from colorama import Fore + + +COLORS = { + "black": Fore.BLACK, + "blue": Fore.BLUE, + "cyan": Fore.CYAN, + "green": Fore.GREEN, + "magenta": Fore.MAGENTA, + "red": Fore.RED, + "white": Fore.WHITE, + "yellow": Fore.YELLOW, + None: None +} + + +def ncprint(*objects, color=None, sep=" ", **kwargs): + return cprint(*objects, color=None, sep=sep, **kwargs) + +def cprint(*objects, color=None, sep=" ", **kwargs): + color = get_color(color) + text = flatten_strings(objects, sep) + return _print(color, text, sep, kwargs) + +def get_color(color): + try: + return COLORS[color] + except KeyError as exc: + color = repr(color) + allowed = tuple(COLORS.keys()) + raise ValueError(f"{color} not from {allowed}") from exc + +def flatten_strings(objects, sep): + return sep.join(str(i) for i in objects) + +def _print(color, text, sep, kwargs): + if color is not None: + text = color + text + Fore.RESET + return print(text, sep=sep, **kwargs) + + +