Message169335
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 |
|
Date |
User |
Action |
Args |
2012-08-29 04:26:24 | rhettinger | set | recipients:
+ rhettinger |
2012-08-29 04:26:24 | rhettinger | set | messageid: <1346214384.31.0.130580797931.issue15805@psf.upfronthosting.co.za> |
2012-08-29 04:26:23 | rhettinger | link | issue15805 messages |
2012-08-29 04:26:23 | rhettinger | create | |
|