thread specific sys.stdout?

Diez B. Roggisch deetsNOSPAM at web.de
Wed Sep 15 17:14:47 EDT 2004


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()


-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list