2014-01-06 03:26:32 +01:00
|
|
|
from __future__ import absolute_import
|
2013-12-18 15:58:58 +01:00
|
|
|
from threading import Thread
|
|
|
|
|
|
|
|
try:
|
|
|
|
from Queue import Queue, Empty
|
|
|
|
except ImportError:
|
|
|
|
from queue import Queue, Empty # Python 3.x
|
|
|
|
|
|
|
|
|
2014-03-25 14:19:12 +01:00
|
|
|
# Yield STOP from an input generator to stop the
|
|
|
|
# top-level loop without processing any more input.
|
|
|
|
STOP = object()
|
|
|
|
|
|
|
|
|
2013-12-18 15:58:58 +01:00
|
|
|
class Multiplexer(object):
|
|
|
|
def __init__(self, generators):
|
|
|
|
self.generators = generators
|
|
|
|
self.queue = Queue()
|
|
|
|
|
|
|
|
def loop(self):
|
|
|
|
self._init_readers()
|
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
2014-03-25 14:19:12 +01:00
|
|
|
item = self.queue.get(timeout=0.1)
|
|
|
|
if item is STOP:
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
yield item
|
2013-12-18 15:58:58 +01:00
|
|
|
except Empty:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def _init_readers(self):
|
|
|
|
for generator in self.generators:
|
|
|
|
t = Thread(target=_enqueue_output, args=(generator, self.queue))
|
|
|
|
t.daemon = True
|
|
|
|
t.start()
|
|
|
|
|
|
|
|
|
|
|
|
def _enqueue_output(generator, queue):
|
|
|
|
for item in generator:
|
|
|
|
queue.put(item)
|