thread specific sys.stdout?

Alex Martelli aleaxit at yahoo.com
Thu Sep 16 23:23:29 CEST 2004


Diez B. Roggisch <deetsNOSPAM at web.de> wrote:

> aurora wrote:
> 
> > This may sound a little crazy. I capture the output of one class by
> > redirecting the sys.stdout. However the is another threading running at
> > the same time and occasionaly it output some messages to the redirected
> > sys.stdout irreleveant to the output I want to capture. Is there a way to
> > redirect output specific to some threads?
> 
> You could replace sys.stdout by a class that splits the written text
> depending on the current thread. It might look roughly like this:
> 
> class ThreadPrinter:
>     def __init__(self):
>         _.fhs = {}
> 
>     def write(self, value):
>         f = _.fhs.get(threading.currentThread(),
> open(get_some_nice_file_name(), "w")
>         f.write(value)
>         _.fhs[threading.currentThread()] = f

Not a bad general idea, but you need a better implementation of the
"thread-local storage" design pattern than just a bare dictionary like
this 'fhs' dict.  In Python 2.4, threading.local gives you such an
implementation.  If you need to work in Python 2.3, it's more work, but
there are cookbook recipes (on Activestate's site) which can help.


Alex



More information about the Python-list mailing list