redirecting sys.stdout and threads

Chris Liechti cliechti at gmx.net
Thu Nov 22 13:54:38 EST 2001


Peter Hansen <peter at engcorp.com> wrote in
news:3BFC9620.EF571437 at engcorp.com: 

> Chris Liechti wrote:
>> 
>> the standard way to redirect outputs of print statements is to assign
>> an other file to sys.stdout and/or sys.stderr. the editors (idle,
>> pythonwin, wxWindows pyshell, etc.) are an example for this. 
>> 
>> 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
> (I called it the Doppleganger class) which can be installed
> in place of sys.stdout.  When the write() method of the
> Doppleganger was called, it would check to see if the current 
> thread object had a predefined name which referenced a
> Redirector object with another write() method.  If it did, it 
> would pass the data on to that object's write() method.  
> Otherwise it would just print to the original stdout.
> 
> This allowed creation of, among other things, a redirector
> which wrote to a socket, and one which wrote to a log file,
> depending on what object a particular had installed as
> its redirector.
> 
> 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...

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list