Threads with independant IO streams
Alex Martelli
aleax at aleax.it
Thu Mar 13 12:03:51 EST 2003
Jason Harper wrote:
> Is it possible for multiple Python threads to have their own sys.stdout
> (and other streams), such that plain `print' statements in each thread
> send output to different places?
>
> I have managed to create a separate sys module for each thread (using an
> import hook much like rexec uses), and can have sys.stdout.write()
> output go to different places, but print output still goes to the stdout
> defined in the 'real' sys module.
So, the solution might be to use as "the" sys.stdout a clever class
that does the demuxing you're looking for, e.g.:
import sys, threading
class PerThreadOutput(object):
def __init__(self):
self.baseout = sys.stdout
self.ptout = {}
sys.stdout = self
def setOut(self, threadName, stream):
self.ptout[threadName] = stream
def write(self, data):
ctname = threading.currentThread().getName()
stream = self.ptout.get(ctname, self.baseout)
stream.write(data)
PerThreadOutput()
You'll need to add locking to taste, and a similarly clever hack to
have softspace be also per-thread (via a property, for example), but
I hope the general idea can help you.
Alex
More information about the Python-list
mailing list