加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python-3.x – 等待Python异步生成器

发布时间:2020-12-20 11:56:59 所属栏目:Python 来源:网络整理
导读:假设我有两个异步生成器: 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元组,其中包含两个元组的最新
假设我有两个异步生成器:

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.

免责声明:我是项目维护者.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读