Redirect stdout

Alex Martelli aleaxit at yahoo.com
Wed Apr 11 12:20:37 EDT 2001


"Fernando Rodríguez" <spamers at must.die> wrote in message
news:ihe8dtcr8eau6to14996pjm789s7lqohna at 4ax.com...
> How can I temporarely redirect stdout to a string?

import cStringIO, sys

astring = cStringIO.StringIO()
saveout = sys.stdout
sys.stdout = astring

try:
    # whatever code you want to
    # run with "redirected" stdout
    print "hello there!"
finally:
    # make sure stdout is restored
    sys.stdout = saveout

# and here is all the output that
# was done 'redirected'...:
print astring.getvalue()


Alex






More information about the Python-list mailing list