如何等待(不使用 await 关键字)异步任务完成并检索结果?
How to await (without using the await keyword) for an asyncio task to complete and retrieve the result?
我们知道,在 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())
将协程添加到事件循环中,其中 returns a Task object.
在我的场景中,任务被添加到 >>> 现有的 运行ning 循环 <<<,随后的代码将继续执行而无需等待task/coroutine 到此结束。当然也可以在任务结束时执行回调函数 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()
,因为循环已经 运行ning(除非我们 运行 异步代码是一个单独的进程并创建一个 new 该进程内的事件循环,但这不是我正在寻找的用例)。
所以我的问题是 如何在异步任务(或任务组)上等待(从异步函数外部 = 不使用 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)
如果没有并发执行,这在逻辑上是不可能的。等待异步函数之外的东西意味着阻塞当前线程。但如果当前线程被阻塞,则任务不可能运行。您实际上可以编写这样的代码(例如,等待 threading.Event 对象,它设置在您的任务结束时)。但是程序会因为我给的原因死锁
我们知道,在 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())
将协程添加到事件循环中,其中 returns a Task object.
在我的场景中,任务被添加到 >>> 现有的 运行ning 循环 <<<,随后的代码将继续执行而无需等待task/coroutine 到此结束。当然也可以在任务结束时执行回调函数 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()
,因为循环已经 运行ning(除非我们 运行 异步代码是一个单独的进程并创建一个 new 该进程内的事件循环,但这不是我正在寻找的用例)。
所以我的问题是 如何在异步任务(或任务组)上等待(从异步函数外部 = 不使用 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)
如果没有并发执行,这在逻辑上是不可能的。等待异步函数之外的东西意味着阻塞当前线程。但如果当前线程被阻塞,则任务不可能运行。您实际上可以编写这样的代码(例如,等待 threading.Event 对象,它设置在您的任务结束时)。但是程序会因为我给的原因死锁