From 20dc480123cc555cc06f9d1d131c828174aaa8cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Thalheim?= Date: Wed, 26 Jul 2023 14:33:15 +0200 Subject: [PATCH] add tty module to color text --- pkgs/clan-cli/clan_cli/tty.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 pkgs/clan-cli/clan_cli/tty.py diff --git a/pkgs/clan-cli/clan_cli/tty.py b/pkgs/clan-cli/clan_cli/tty.py new file mode 100644 index 0000000..5d930ec --- /dev/null +++ b/pkgs/clan-cli/clan_cli/tty.py @@ -0,0 +1,25 @@ +import sys +from typing import IO, Any, Callable + + +def is_interactive() -> bool: + """Returns true if the current process is interactive""" + return sys.stdin.isatty() and sys.stdout.isatty() + + +def color_text(code: int, file: IO[Any] = sys.stdout) -> Callable[[str], None]: + """ + Print with color if stderr is a tty + """ + + def wrapper(text: str) -> None: + if file.isatty(): + print(f"\x1b[{code}m{text}\x1b[0m", file=file) + else: + print(text, file=file) + + return wrapper + + +warn = color_text(91, file=sys.stderr) +info = color_text(92, file=sys.stderr)