redirecting sys.stdout and threads

Peter Hansen peter at engcorp.com
Thu Nov 22 01:07:28 EST 2001


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.

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



More information about the Python-list mailing list