"Write to a file" question please?

David Bolen db3l at fitlinxx.com
Wed Jul 5 20:50:11 EDT 2000


"Alex Martelli" <alex at magenta.com> writes:

> Another alternative:
> 
>     import sys
>     sys.stdout = OUT
>     print "Number =", number
>     sys.stdout = sys.__stdout__
>     OUT.close()
> 
> By assigning an opened file to sys.stdout
> you temporarily "redirect" the output of
> normal "print" to that file; you can then
> go back to normal using sys.__stdout__,
> which keeps the ORIGINAL value.  Not worth
> it for writing just a few things, but fine
> if you have some function doing a lot of
> output with print, for example.

Just one thought - unless you know that you aren't going to be
embedded in some other module (and given how easy it is for one module
to import another, who can say for sure :-)), it's safer to save the
value of sys.stdout and restore to that rather than explicitly using
sys.__stdout__.  If the surrounding environment had already
"redirected" sys.stdout, this code would have an unintended
side-effect of undoing that redirection.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list