redirecting sys.stdout and threads

Peter Hansen peter at engcorp.com
Thu Nov 22 19:08:13 EST 2001


Chris Liechti wrote:
> 
> Peter Hansen <peter at engcorp.com> wrote:
> 
> > Chris Liechti wrote:
> >> but what can you do if more than one thread wants to use redirection?
> >
> > The way I handled this was to write a redirector object
[...]
> > There might be easier methods, but after I noted that the
> > interpreter (apparently) records sys.stdout *on startup* and
> > uses that one reference for all subsequent print statements
> > (effectively "fixing" destination of printed output),
> > I saw no other choice.
> >
> 
> I realized that my example script modified the one and only sys instance
> that is common for all threads, hence its logic that all threads print to
> the same stream.
> 
> I'm mainly interested in redirecting output of an exec statement and you
> can specify a global dict for exec: "exec string in myglobals" so i could
> make a copy of the original globals and then modify the dict to use a copy
> of the sys module with redirected outputs.
> i'll have to play around with this...

I believe this method will fail.  The phenomenon I believe I 
observed and verified in the source was that the *print* command
would use an invariant reference to the original sys module,
and therefore any subsequent attempts to fake the system into
using a different sys would fail.  You have to replace sys.stdout
itself, while leaving sys alone.  As I said, I might have 
misinterpreted this, but it was the only way I could get it to work.

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list