我们知道,在async函数内部,代码不会继续执行,直到等待的协程完成执行:
await coro()
# or
await asyncio.gather(coro_1(), coro_2())
# Code below will run AFTER the coroutines above finish running = desired effect
在函数外部(或内部),async可以将协程添加到事件循环中asyncio.create_task(coro()),返回一个Task 对象。
在我的场景中,任务被添加到 >>> 现有的运行循环 <<<中,随后的代码将继续执行,而无需等待该任务/协程完成。当然,可以在任务结束时执行回调函数task_obj.add_done_callback(callback_func)。
asyncio.create_task(coro())在 Jupyter Notebooks / Jupyter Lab 上特别有用,因为 Jupyter 在后台运行事件循环。调用asyncio.get_event_loop()将检索 Jupyter 的事件循环。在 Jupyter Notebook 中,我们无法调用asyncio.run(coro())或者loop.run_until_complete()因为循环已经在运行(除非我们在一个单独的进程中运行异步代码并在该进程中创建一个新的事件循环,但这不是我正在寻找的用例)。
所以我的问题是我如何才能等待(从异步函数外部=不使用await关键字)异步任务(或任务组)在执行后面的代码之前完成并检索结果?
tsk_obj = asyncio.create_task(coro()) # adds task to a (in my case) running event loop
# QUESTION:
# What can be done to await the result before executing the rest of the code below?
print('Result is:', tsk_obj.result())
# ^-- this of course will execute immediately = NOT the desired effect
# (the coroutine is very likely still running on the event loop and the result is not ready)
白板的微信
相关分类