假设我有两个异步生成器:
async def get_rules(): while True: yield 'rule=1' asyncio.sleep(2) async def get_snapshots(): while True: yield 'snapshot=1' asyncio.sleep(5)
我想将它们合并到一个异步生成器中,该生成器返回2元组,其中包含两个元组的最新值.组合最新.
做这个的最好方式是什么?
解决方法
你可能想看看
aiostream,特别是
stream.merge和
stream.accumulate:
import asyncio from itertools import count from aiostream import stream async def get_rules(): for x in count(): await asyncio.sleep(2) yield 'rule',x async def get_snapshots(): for x in count(): await asyncio.sleep(5) yield 'snapshot',x async def main(): xs = stream.merge(get_rules(),get_snapshots()) ys = stream.map(xs,lambda x: {x[0]: x[1]}) zs = stream.accumulate(ys,lambda x,e: {**x,**e},{}) async with zs.stream() as streamer: async for z in streamer: print(z) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close()
输出:
{} {'rule': 0} {'rule': 1} {'rule': 1,'snapshot': 0} {'rule': 2,'snapshot': 0} [...]
有关详细信息,请参阅project page和documentation.
免责声明:我是项目维护者.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。