catch output of threads
William
wilk-spamout at flibuste.net
Sat Nov 30 04:53:04 EST 2002
Jeff Epler <jepler at unpythonic.net> writes:
> 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.
Thanks, really brilliant idea !
>
> "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)
>
--
William Dode - http://flibuste.net
More information about the Python-list
mailing list