catch output of threads

Jeff Epler jepler at unpythonic.net
Fri Nov 29 16:09:04 EST 2002


You can make sys.stdout an object which uses thread.get_ident() to do
"something special" with data written depending on what thread wrote it.

"ThreadedOutputThing" just prefixes all lines of output with the
thread ID.  "ThreadedOuputThing2" creates files that contain the PID
and TID.  TOT2 keeps a cache of open file objects, but never has more
than ten open at once.

You could do other things, depending on your needs.

Jeff

import sys, thread, time, os

class ThreadedOutputThing:
    def __init__(self, f = sys.stdout):
        self.f = f

    def write(self, s):
        i = thread.get_ident()
        print >>self.f, "Thread %5d: %r" % (i, s)

class ThreadedOutputThing2:
    def __init__(self, b = "%d-%%d.out" % os.getpid(), of="a"):
        self.b = b
        self.of = of
        self.d = {}

    def write(self, s):
        i = thread.get_ident()
        d = self.d
        if not d.has_key(i):
            if len(d) > 10:
                d.popitem()[1].close()
            d[i] = open(self.b % i, self.of)
        d[i].write(s)

def f():
    print "In function f, thread %d" % thread.get_ident()

if __name__ == '__main__':
    #sys.stdout = ThreadedOutputThing()
    sys.stdout = ThreadedOutputThing2()
    thread.start_new_thread(f, ())
    thread.start_new_thread(f, ())
    thread.start_new_thread(f, ())
    time.sleep(1)




More information about the Python-list mailing list