python - 如何将 AsyncIterator 转换为 Iterator?
问题描述
是否可以在 AsyncIterator 周围包装一个函数以获取(同步)迭代器?
我能够将 AsyncIterator 转换为 List 并将其用作 Iterator,但希望不转换为 Int
class AsyncToSyncIterableUtils(Generic[T]):
@staticmethod
def sync_all(iterable: AsyncIterable[T]) -> Iterable[T]:
results:List[T] = []
async def _wrapper():
async for m in iterable:
results.append(m)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(_wrapper())
finally:
loop.run_until_complete(loop.shutdown_asyncgens()) # see: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.shutdown_asyncgens
loop.close()
return results
解决方案
推荐阅读
- python - 出现次数的数组
- angular - clrDgSingleSelected 在清晰版本 3 中抛出错误
- macos - 如何调试调用 NSMenuItem 上的 undo 命令导致的崩溃?
- sas - SAS:在数据步中添加字符变量而不预先设置长度
- node.js - NodeJS/Express 多个路由文件之间的共享功能
- node.js - heroku Postgres - 续集:主机没有 pg_hba.conf 条目
- c# - 已发布的文件夹名称和清单未更新
- java - 空集合转换为空
- r - 字符串似乎是一个空格字符,但不是
- mysql - 有没有办法将查询结果临时存储在 mySQL 中?