nghung270192 / colorama

Automatically exported from code.google.com/p/colorama
BSD 3-Clause "New" or "Revised" License
0 stars 0 forks source link

Support context manager syntax #28

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
It'd be nice to turn colorized output on and off with `with` rather than either 
init() or writing by hand, especially when other modules want to modify 
sys.stdout.  Here's an example implementation:

import sys
from colorama import Fore, AnsiToWin32

class ConvertedOutput(object):
    def __init__(self, *AnsiToWin32Args, **kwargs):
        self._AnsiArgs = AnsiToWin32Args
        self._set_stderr = kwargs.get('stderr', None)
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout   = AnsiToWin32(sys.stdout, *self._AnsiArgs)
        if self._set_stderr:
            sys.stderr = AnsiToWin32(sys.stderr, *self._AnsiArgs)
    def __exit__(self, type, value, traceback):
        sys.stdout = self._stdout

And example usage:

with ConvertedOutput():
    print('%sThis text is red%s' % (Fore.RED, Fore.RESET))

print('%sThis text is surrounded by junk%s' % (Fore.RED, Fore.RESET))

Original issue reported on code.google.com by st...@3xile.com on 8 Aug 2011 at 10:56

GoogleCodeExporter commented 9 years ago
Many thanks for the report, and apologies for letting this lie dormant for 
years.

That does sound useful - and perhaps is the way colorama should have worked by 
default. Let me think about it and see whether it makes sense to add it.

Original comment by tart...@gmail.com on 20 Apr 2014 at 9:35