您可以使用aiostream.stream.merge http://aiostream.readthedocs.io/en/latest/operators.html#aiostream.stream.merge:
from aiostream import stream
async def main():
runs = [test_gen(i) for i in range(3)]
async for x in stream.merge(*runs):
print(f'{x} yielded')
在一个安全环境 http://aiostream.readthedocs.io/en/latest/core.html#aiostream.core.Stream.stream确保迭代后正确清理生成器:
async def main():
runs = [test_gen(i) for i in range(3)]
merged = stream.merge(*runs)
async with merged.stream() as streamer:
async for x in streamer:
print(f'{x} yielded')
或者使用使其更紧凑pipes http://aiostream.readthedocs.io/en/latest/operators.html#pipe-lining:
from aiostream import stream, pipe
async def main():
runs = [test_gen(i) for i in range(3)]
await (stream.merge(*runs) | pipe.print('{} yielded'))
更多示例在文档 http://aiostream.readthedocs.io/en/latest/examples.html.
处理@nirvana-msu 评论
通过准备相应的源,可以识别产生给定值的生成器:
async def main():
runs = [test_gen(i) for i in range(3)]
sources = [stream.map(xs, lambda x: (i, x)) for i, xs in enumerate(runs)]
async for i, x in stream.merge(*sources):
print(f'ID {i}: {x}')