如何在python36中获取当前正在运行的EventLoop?

Ada*_*mer 5 python-asyncio python-3.6

我知道在python37中我们有一个新的api asyncio.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())
Run Code Online (Sandbox Code Playgroud)

use*_*342 8

在 Python 3.6 中你可以使用它asyncio.get_event_loop()来达到同等的效果。

根据文档,它相当于调用get_event_loop_policy().get_event_loop(),而调用又被记录为在从协程调用时返回“当前正在运行的事件循环”。

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

请注意,get_event_loop从协程调用时返回运行循环对于 Python 3.6 和 3.5.3 来说是新功能。在这些版本之前,get_event_loop总是返回与当前线程关联的事件循环,这可能是与实际运行的循环不同的循环。这get_event_loop()从根本上来说是不可靠的,也是旧的异步代码会到处传递参数的原因loop。更多详细信息请参见此处