python - 在 Python 中加入多个异步生成器
问题描述
我想监听来自同一对象的多个实例的事件,然后将此事件流合并到一个流中。例如,如果我使用异步生成器:
class PeriodicYielder:
def __init__(self, period: int) -> None:
self.period = period
async def updates(self):
while True:
await asyncio.sleep(self.period)
yield self.period
我可以成功监听来自一个实例的事件:
async def get_updates_from_one():
each_1 = PeriodicYielder(1)
async for n in each_1.updates():
print(n)
# 1
# 1
# 1
# ...
但是我怎样才能从多个异步生成器中获取事件呢?换句话说:我如何按照它们准备好生成下一个值的顺序遍历多个异步生成器?
async def get_updates_from_multiple():
each_1 = PeriodicYielder(1)
each_2 = PeriodicYielder(2)
async for n in magic_async_join_function(each_1.updates(), each_2.updates()):
print(n)
# 1
# 1
# 2
# 1
# 1
# 2
# ...
stdlib 或 3rd 方模块中是否有这样的magic_async_join_function ?
解决方案
您可以使用精彩的aiostream库。它看起来像这样:
import asyncio
from aiostream import stream
async def test1():
for _ in range(5):
await asyncio.sleep(0.1)
yield 1
async def test2():
for _ in range(5):
await asyncio.sleep(0.2)
yield 2
async def main():
combine = stream.merge(test1(), test2())
async with combine.stream() as streamer:
async for item in streamer:
print(item)
asyncio.run(main())
结果:
1
1
2
1
1
2
1
2
2
2
推荐阅读
- flask - MongoClient 在 fork 之前打开。仅创建 MongoClient Flask
- android - 使用 Camera 2 API 捕获图像而不使预览不连贯
- sql - 基于部分字符串匹配连接两个表
- wordpress - 没有 CSS 显示;OceanWP 儿童主题
- x86 - 哪种内存访问架构具有 i9 处理器?
- javascript - 通过 javascript / ajax 获取 php 循环的值
- eclipse - 如何使用 Maven Tycho 构建 Junit5 测试
- c# - C# - 提高搜索时的性能
- ms-access - 如何触发记录选择?
- json - Spring boot 和 Angular 中的 JSON 操作