thread specific sys.stdout?

aurora aurora00 at gmail.com
Wed Sep 15 18:58:24 EDT 2004


On Wed, 15 Sep 2004 23:14:47 +0200, 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
>
> Now before starting your threads, replace sys.stdout with an instance of
> ThreadPrinter:
>
> sys.stdout = ThreadPrinter()
>
>

Thanks this is a nice idea. I hope Python would actually support the '_'  
syntax. The self really reduce readablity, especially if you have several  
of them in one line.




More information about the Python-list mailing list