sys.stdout redirection

Jeff Epler jepler at unpythonic.net
Mon Jul 19 16:58:54 CEST 2004


First, a pair of style issues:
> boolStdOut = True
blah.  Don't call a list "listX", call it "x". Don't call a bool
"boolY", call it "y".  Don't call it "boolStdOut", call it
"replaceStdout" or something

> if boolStdOut == 1:
Don't compare a boolean to anything, just use it in a boolean context:
    if replaceStdout:

Now, to your real problem.  I don't get a "ValueError" when running the
snippet of code that you included in your post, but you mention that
your real application is multithreaded.  Imagine for a moment that some
other thread is running interleaved with the code you pasted and that it
executes a "print" statement
>     sys.stdout.close()
# HERE
>     sys.stdout = oldStd

Well, sys.stdout *does* name a closed file at this point.

You could avoid this condition by writing
     oldStd = sys.stdout
     tempStd = sys.stdout = open("c:\\std.out", "w")
     print "This is Redirected stdout to the file"
     #sys.stdout.flush()  # This is redundant! close() flushes implicitly
     sys.stdout = oldStd
     tempStd.close()
... but if different threads print to stdout, and you don't synchronize
the printing with the pointing of stdout to different files, you'll end
up with output going to the wrong place.

I recommend not using bare "print", but using "print >>f" or
"f.write()", with "f" being associated in some way with the current
thread, which side-steps the problems associated with modifying a global
variable which is used by multiple threads.

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040719/586d4e05/attachment.pgp>


More information about the Python-list mailing list