(python) colour printing with decorator in a function

后端 未结 3 1732
醉酒成梦
醉酒成梦 2020-12-17 05:09

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<

3条回答
  •  北海茫月
    2020-12-17 05:37

    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)
    

提交回复
热议问题