【发布时间】:2019-09-12 17:46:37
【问题描述】:
我有一个正在运行 asyncio 事件循环的 python 脚本,我想知道如何在不阻塞事件循环的情况下迭代一个大列表。从而保持循环运行。
我尝试使用 __aiter__ 和 __anext__ 创建一个自定义类,但没有成功,我还尝试创建一个 async function 产生结果但它仍然阻塞。
目前:
for index, item in enumerate(list_with_thousands_of_items):
# do something
我尝试过的自定义类:
class Aiter:
def __init__(self, iterable):
self.iter_ = iter(iterable)
async def __aiter__(self):
return self
async def __anext__(self):
try:
object = next(self.iter_)
except StopIteration:
raise StopAsyncIteration
return object
但这总是会导致
TypeError: 'async for' received an object from __aiter__ that does not implement __anext__: coroutine
我制作的async function 可以工作但仍然阻塞事件循环是:
async def async_enumerate(iterable, start:int=0):
for idx, i in enumerate(iterable, start):
yield idx, i
【问题讨论】:
-
你对列表中的每一项都做了什么?
-
你考虑过类似 ProcessPoolExecutor 的东西吗?它可能非常适合您的问题。
-
@rdas 我将每个项目添加到一个字符串中
-
@RafaëlDera 很遗憾,我从未听说过 ProcessPoolExecutor
-
您的
__aiter__应该是def,而不是async def。
标签: python python-3.x list asynchronous python-asyncio