| Store | Cart

writing output to file

From: Alex Martelli <ale...@aleax.it>
Fri, 12 Jul 2002 09:24:02 GMT
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

Recent Messages in this Thread
Allan Wermuth Jul 11, 2002 07:25 pm
Ralf Claus Jul 11, 2002 07:17 pm
Mark McEahern Jul 11, 2002 07:27 pm
Alex Martelli Jul 11, 2002 08:01 pm
Allan Wermuth Jul 11, 2002 08:50 pm
Emile van Sebille Jul 12, 2002 12:00 am
Stephen D Evans Jul 11, 2002 08:35 pm
Hans Nowak Jul 11, 2002 10:18 pm
Alex Martelli Jul 12, 2002 09:24 am
Messages in this thread
Previous post: A better self