python如何在异步IO生成器运行时提前返回

2024-05-23 16:34:17 发布

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

我想返回async generator的第一个元素,并处理剩余的值,而不会像fire and forget那样返回。如何在python中尽早返回协同程序? 将迭代器传递给asyncio.create_task后,它不会打印剩余的值

import asyncio
import time


async def async_iter(num):
    for i in range(num):
        await asyncio.sleep(0.5)
        yield i

async def handle_remains(it):
    async for i in it:
        print(i)

async def run() -> None:
    it = async_iter(10)
    async for i in it:
        print(i)
        break
    # await handle_remains(it) 
    # want to make this `fire and forget`(no await), expecting just printing the remainning values.
    asyncio.create_task(handle_remains(it))
    return i

if __name__ == '__main__':
    asyncio.run(run())
    time.sleep(10)

Tags: andruninasynciofortaskasyncdef
1条回答
网友
1楼 · 发布于 2024-05-23 16:34:17

您对代码已经很熟悉了,但还不是很熟悉(请参见我上面的评论)。简而言之,创建Task是不够的:任务需要运行:

task = asyncio.create_task(handle_remains(it))  # Creates a Task in `pending` state.
await task  # Run the task, i.e. execute the wrapped coroutine.

一个任务,连同协同程序和未来,是一个“Awaitable”。事实上:

When a coroutine is wrapped into a Task with functions like asyncio.create_task() the coroutine is automatically scheduled to run soon.

注意“scheduled to run soon”,现在您必须确保通过调用await来实际运行任务,这是一个关键字,它

is used to obtain a result of coroutine execution.

相关问题 更多 >