异步迭代器在

2024-09-19 20:41:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在实现一个与async for一起使用的异步迭代器,该迭代器应该以一个(大部分)固定的间隔返回一个新值。在

我们可以用一个简单的时钟来说明这种迭代器,它每~n秒增加一个计数器:

import asyncio

class Clock(object):
    def __init__(self, interval=1):
        self.counter = 0
        self.interval = interval
        self.tick = asyncio.Event()
        asyncio.ensure_future(self.tick_tock())

    async def tick_tock(self):
        while True:
            self.tick.clear()
            await asyncio.sleep(self.interval)
            self.counter = self.__next__()
            self.tick.set()

    def __next__(self):
        self.counter += 1
        return self.counter

    def __aiter__(self):
        return self

    async def __anext__(self):
        await self.tick.wait()
        return self.counter

有没有比使用asyncio.Event更好或更干净的方法?此迭代器上将有多个协程async for。在


Tags: selfeventasyncioforasync间隔returndef
2条回答

如果您使用的是python3.6+,那么可以使用可读性更强的asynchronous generators。在

async def Clock(interval=1):
    counter = 0
    while True:
        await asyncio.sleep(interval)
        counter += 1
        yield counter


async def main():
    async for i in Clock(1):
        print(i)
        if i == 4:
            break


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(main())
    finally:
        loop.run_until_complete(loop.shutdown_asyncgens())
        loop.close()

在我看来,你的方法很好。请注意,从python3.6开始,您还可以使用asynchronous generators

async def clock(start=0, step=1, interval=1.):
    for i in count(start, step):
        yield i
        await asyncio.sleep(interval)

但是,您不能在多个协同程序之间共享它们。您必须在任务中运行时钟,并通过异步迭代接口使数据可用,这实际上就是您在代码中所做的工作。这是一个possible implementation。在

相关问题 更多 >