Neal Becker
2/11/2008 3:37:00 PM
This will work for stdout:
from __future__ import with_statement
from contextlib import contextmanager
import sys
@contextmanager
def redirect(newfile):
orig_stdout = sys.stdout
sys.stdout = newfile
yield
sys.stdout = orig_stdout
if __name__ == "__main__":
with redirect (open('stdout', 'w')):
print "hello"
print "we're back"
But now, a harder puzzle that I'm stumped on. Rewrite the above so that it
doesn't hardcode sys.stdout, ie:
def redirect (newfile, oldfile=None)
where default oldfile is sys.stdout. This seems much trickier.