-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathColorizePrintStream.py
More file actions
38 lines (29 loc) · 914 Bytes
/
ColorizePrintStream.py
File metadata and controls
38 lines (29 loc) · 914 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import sys
import colorama
from colorama import Fore, Back, Style
import re
from typing import TextIO
class ColorizedWrapper(object):
def __init__(self, stream: TextIO, patterns : list[tuple[str, colorama.ansi.AnsiFore|colorama.ansi.AnsiBack|colorama.ansi.AnsiStyle]]):
self.patterns = patterns
self.stream = stream
def install_stdout(self):
sys.stdout = self
def uninstall_stdout(self):
sys.stdout = self.stream
def install_stderr(self):
sys.stderr = self
def uninstall_stderr(self):
sys.stderr = self.stream
def write(self, text):
# Check each pattern and apply the first matching color
for pattern, color in self.patterns:
if re.search(pattern, text):
colored_text = color + text + Fore.RESET
self.stream.write(colored_text)
break
else:
# If no pattern matches, write the text as is
self.stream.write(f'{text}')
def flush(self):
self.stream.flush()