70 lines
1.7 KiB
Python
70 lines
1.7 KiB
Python
"""WizardKit: ANSI control/escape functions"""
|
|
# vim: sts=2 sw=2 ts=2
|
|
|
|
import itertools
|
|
import logging
|
|
|
|
from typing import Iterable
|
|
|
|
# STATIC VARIABLES
|
|
LOG = logging.getLogger(__name__)
|
|
COLORS = {
|
|
'CLEAR': '\033[0m',
|
|
'RED': '\033[31m',
|
|
'RED_BLINK': '\033[31;5m',
|
|
'ORANGE': '\033[31;1m',
|
|
'ORANGE_RED': '\033[1;31;41m',
|
|
'GREEN': '\033[32m',
|
|
'YELLOW': '\033[33m',
|
|
'YELLOW_BLINK': '\033[33;5m',
|
|
'BLUE': '\033[34m',
|
|
'PURPLE': '\033[35m',
|
|
'CYAN': '\033[36m',
|
|
}
|
|
|
|
|
|
# Functions
|
|
def clear_screen() -> None:
|
|
"""Clear screen using ANSI escape."""
|
|
print('\033c', end='', flush=True)
|
|
|
|
|
|
def color_string(
|
|
strings: Iterable[str] | str,
|
|
colors: Iterable[str | None] | str,
|
|
sep=' ',
|
|
) -> str:
|
|
"""Build colored string using ANSI escapes, returns str."""
|
|
data = {'strings': strings, 'colors': colors}
|
|
msg = []
|
|
|
|
# Convert input to tuples of strings
|
|
for k, v in data.items():
|
|
if isinstance(v, str):
|
|
# Avoid splitting string into a list of characters
|
|
data[k] = (v,)
|
|
try:
|
|
iter(v)
|
|
except TypeError:
|
|
# Assuming single element passed, convert to string
|
|
data[k] = (str(v),)
|
|
|
|
# Build new string with color escapes added
|
|
for string, color in itertools.zip_longest(data['strings'], data['colors']):
|
|
color_code = COLORS.get(str(color), COLORS['CLEAR'])
|
|
msg.append(f'{color_code}{string}{COLORS["CLEAR"]}')
|
|
|
|
# Done
|
|
return sep.join(msg)
|
|
|
|
|
|
def strip_colors(string: str) -> str:
|
|
"""Strip known ANSI color escapes from string, returns str."""
|
|
LOG.debug('string: %s', string)
|
|
for color in COLORS.values():
|
|
string = string.replace(color, '')
|
|
return string
|
|
|
|
|
|
if __name__ == '__main__':
|
|
print("This file is not meant to be called directly.")
|