python-3.x – 等待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元组,其中包含两个元组的最新值.组合最新.

做这个的最好方式是什么?

解决方法

你可能想看看 aiostream,特别是 stream.mergestream.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 pagedocumentation.

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

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...