writing output to file

Alex Martelli aleax at aleax.it
Fri Jul 12 05:24:02 EDT 2002


Hans Nowak wrote:
        ...
>> I would appreciate if someone would help me out.
> 
> Redirect sys.stdout:
> 
> oldstdout = sys.stdout
> sys.stdout = open("some file", "w") # or any file(-like) object
> 
> # your code here; print statements should be redirected
> 
> # clean up
> sys.stdout = oldstdout

"Yes, but" -- this is very fragile code: any exception from the
part "your code here", and you're left with sys.stdout pointing
who knows where.  A more robust approach:


oldstdout = sys.stdout
newstdout = open("whatever", "w")
sys.stdout = newstdout

try:
    # your code here
finally:
    # GUARANTEED cleanup
    sys.stdout = oldstdout
    newstdout.close()


This kind of task is exactly what try/finally is for: ENSURE that
cleanup code runs, no matter whether a certain piece of code
terminates normally or by propagating exceptions.

Singling out newstdout here may be overkill, but I'd fear
exceptions from the close method in the case of file-like
objects, thus the braces-and-belt approach.  An exception
in a finally cause is not the end of the world, but I feel
safer knowing that I HAVE restored sys.stdout anyway, just
in case such an exception DOES arise:-).


Alex




More information about the Python-list mailing list