【问题标题】:How to get currently running EventLoop in python36?如何在 python36 中获取当前正在运行的 EventLoop?
【发布时间】:2019-06-24 16:17:21
【问题描述】:

我知道在python37中我们有一个新的apiasyncio.get_running_loop(),它很容易使用,让我们在调用协程时不需要显式传递eventloop。

我想知道我们是否可以使用任何方法在 python36 中获得相同的效果?

# which allows us coding conveniently with this api:
import asyncio

async def test():
    print("hello world !")

async def main():
    loop = asyncio.get_running_loop()
    loop.create_task(test())

asyncio.run(main())

【问题讨论】:

  • @user4815162342 确实,非常感谢!

标签: python-3.6 python-asyncio


【解决方案1】:

在 Python 3.6 中,您可以使用 asyncio.get_event_loop() 获得等效效果。

根据documentation,相当于调用get_event_loop_policy().get_event_loop(),又是documented在协程调用时返回“当前正在运行的事件循环”。

换句话说,当从协程(或从协程调用的函数)调用时,get_event_loopget_running_loop 没有区别,两者都会返回正在运行的循环。只有在没有循环运行时,get_event_loop() 才会继续返回与当前线程关联的循环,而get_running_loop() 会引发异常。只要您在循环实际运行时小心调用get_event_loop(),它将等效于get_running_loop()

注意get_event_loop 从协程调用时返回运行循环是new to Python 3.6 and 3.5.3。在这些版本之前,get_event_loop 将始终返回与当前线程关联的事件循环,这可能是与实际运行的循环不同的循环。这使得get_event_loop() 从根本上不可靠,这也是旧异步代码到处传递loop 参数的原因。更多详情here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多