Redirect stdout to file

Fredrik Lundh fredrik at pythonware.com
Wed Jul 14 14:45:16 EDT 1999


Gaetan Corneau <Gaetan_Corneau at baan.com> wrote:
> I tried it and tought it didn't work, but it seems it was my fault. I did it
> this way:
> 
> from sys import stdout
> stdout = open("out.txt", "w")

to make things a bit clearer, let's rewrite
this slightly.  the above is roughly equivalent
to:

import sys
stdout = sys.stdout
del sys
stdout = open("out.txt", "w")

now, keep in mind that all python variables
are just named pointers.  so:

stdout = sys.stdout

creates a variable called "stdout" in *your*
module, which points to the same thing as
"sys.stdout" currently points to...

stdout = open("out.txt", "w")

replaces the existing variable called "std-
out" with a new one, which points to the
object returned from "open".

"stdout" in your  module, that is.  the "sys"
module isn't affected, and "print" still uses
whatever "sys.stdout" happens to point to...

in contrast,

sys.stdout = open("out.txt", "w")

modifies the "stdout" variable in the sys-
module, which is exactly what you wanted.

or in other words,

    "You Cannot Mutate Simple Variables
    By Assigning To Them"

    (the only way to modify something in place
    is to use a method.  this includes sugared
    methods like __setattr__, __setitem__ etc,
    of course...)

also see:
http://www.pythonware.com/people/fredrik/fyi/fyi06.htm
(seems like you violated the "You Know
Exactly What You're Doing" rule here ;-)

</F>





More information about the Python-list mailing list