How can I decorate a function so that anything it prints to stdout
is in green and anything it prints to stderr
is in red<
Here is my code with termcolor module:
from termcolor import colored
class ColoredOutput:
def __init__(self, org_handle, color, on_color=None, attrs=['bold']):
self.org_handle = org_handle
def wrapper_write(x):
return org_handle.write(colored(x, color=color, on_color=on_color, attrs=attrs))
self.wrapper_write = wrapper_write
def __getattr__(self, attr):
return self.wrapper_write if attr == 'write' else getattr(self.org_handle, attr)
if __name__ == '__main__':
import sys
import colorama # I'm working under windows 7, so i need this module to enable terminal color
colorama.init()
sys.stderr = ColoredOutput(sys.stderr, 'red')
print('This is a test string', file=sys.stderr)