New submission from Raymond Hettinger: The technique of temporarily redirecting stdout could be encapsulated in a context manager.
print('This goes to stdout') with RedirectStdout(sys.stderr): print('This goes to stderr') print('So does this') print('This goes to stdout') The print function already supports redirection but it much be done for every single call to print(). The context manager let's the redirection apply to a batch of statements. The context manager is also useful with existing tools that don't currently provide output redirection hooks: from collections import namedtuple with open('model.py', 'w') as module: with RedirectStdout(module): namedtuple('Person', ['name', 'age', 'email'], verbose=True) import dis with open('disassembly.txt', 'w') as f: with RedirectStdout(f): dis.dis(myfunc) A possible implementation is: class RedirectStdout: ''' Create a context manager for redirecting sys.stdout to another file. ''' def __init__(self, new_target): self.new_target = new_target def __enter__(self): self.old_target = sys.stdout sys.stdout = self.new_target return self def __exit__(self, exctype, excinst, exctb): sys.stdout = self.old_target ---------- components: Library (Lib) messages: 169335 nosy: rhettinger priority: normal severity: normal status: open title: Add stdout redirection tool to contextlib type: enhancement versions: Python 3.4 _______________________________________ Python tracker <rep...@bugs.python.org> <http://bugs.python.org/issue15805> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com