I have two separate generators (in reality they are fed by two separate zero-mq subscribers).
I would like to consume them from the same event loop.
Something conceptually like this:
import time
def gen_one():
while True:
yield 1
time.sleep(1)
def gen_two():
while True:
yield 2
time.sleep(1.3)
for a in gen_one() or gen_two():
print a
# would like to see:
# 1
# 2
# 1
# 2
# 1
# 2
# 1
# 1
# 2
# ...
Note that this is in Python 2.7.
Right now I'm obviously getting 1,1,1,1...
I could somehow nest the second iterator into the first one (not looping, but rather checking if there is something to read), but that, at best, would constrain the rate of the inner consumer to the rate of the outer consumer, which is undesirable.
Note that zip()
is not a good option, for the same reason as mentioned above, in addition to forcing the two generators to have the same rate, which they don't.
Any suggestions on how to achieve this?
Based on suggestions in comments, something like this might work:
from multiprocessing import Process, Queue
import time
def gen_one(queue):
while True:
queue.put(1)
time.sleep(1)
def gen_two(queue):
while True:
queue.put(2)
time.sleep(1.3)
queue = Queue()
p1 = Process(target=gen_one, args=(queue,)).start()
p2 = Process(target=gen_two, args=(queue,)).start()
while True:
a = queue.get()
print a
Which gets the job done.
Not as direct or elegant as I'd like, but definitely not terrible.