Last active
August 20, 2020 07:42
-
-
Save adrian-the-git/3b8eb712702e8d769db38f5f30822bd9 to your computer and use it in GitHub Desktop.
Cross-platform colored text for python3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# If you can write a simpler but still *readable* cross-platform colored text print function please comment! | |
try: | |
from ctypes import windll | |
BLUE, GREEN, CYAN, RED, MAGENTA, YELLOW, GRAY, BOLD, RESET = [*range(1, 9), 7] | |
set_color = (lambda a, b, f=windll.kernel32.SetConsoleTextAttribute, | |
s=windll.kernel32.GetStdHandle(-11): f(s, a | b)) | |
except ImportError: | |
RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, GRAY, BOLD, RESET = [*range(31, 38), 1, 0] | |
set_color = lambda *a: print(f'\033[{";".join(map(str, sorted(a)))}m', end='', flush=True) | |
def cprint(*tokens, last_attr=0, end='\n'): | |
for t in [*tokens, RESET, end]: | |
if isinstance(t, int): | |
set_color(t, last_attr) | |
last_attr = t | |
else: | |
print(f'{t}', end='', flush=True) | |
last_attr = 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
2.0
BOLD, RED
. Just useRed
for normal intensity andRED
for bold (anti-PEP8 but so what?)set_color
transformation to ANSI escapes fromint
s_cprint
doesn't even need to exist except on WindowsExample
3.0?