use 'with' to redirect stdout

Neal Becker ndbecker2 at gmail.com
Mon Feb 11 10:37:18 EST 2008


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.




More information about the Python-list mailing list