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

How to get currently running EventLoop in python36?

我知道在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())

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

根据 documentation, it is equivalent to calling get_event_loop_policy().get_event_loop(), which is in turn documented 到 return "the currently running event loop" 当从协程调用时。

也就是说,从协程调用时(或者从协程调用的函数),get_event_loopget_running_loop没有区别,都会return 运行 循环。只有当没有循环是 运行 时,get_event_loop() 才会保持 returning 与当前线程关联的循环,而 get_running_loop() 将引发异常。只要你小心调用get_event_loop()而一个循环实际上是运行,它就等同于get_running_loop().

请注意 get_event_loop return 从协程调用时 运行 循环是 new to Python 3.6 and 3.5.3. Prior to those versions, get_event_loop would always return the event loop associated with the current thread, which could be a different loop from the one that is actually running. This made get_event_loop() fundamentally unreliable and is the reason why old asyncio code would pass the loop argument everywhere. More details here.