"Asyncio Event Loop is Closed" 获取循环时

"Asyncio Event Loop is Closed" when getting loop

当尝试 运行 文档中给出的 asyncio hello world 代码示例时:

import asyncio

async def hello_world():
    print("Hello World!")

loop = asyncio.get_event_loop()
# Blocking call which returns when the hello_world() coroutine is done
loop.run_until_complete(hello_world())
loop.close()

我收到错误:

RuntimeError: Event loop is closed

我正在使用 python 3.5.3.

在 运行 这段代码示例之前,您已经在全局事件循环中调用了 loop.close()

>>> import asyncio
>>> asyncio.get_event_loop().close()
>>> asyncio.get_event_loop().is_closed()
True
>>> asyncio.get_event_loop().run_until_complete(asyncio.sleep(1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/.../lib/python3.6/asyncio/base_events.py", line 443, in run_until_complete
    self._check_closed()
  File "/.../lib/python3.6/asyncio/base_events.py", line 357, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

您需要创建一个循环:

loop = asyncio.new_event_loop()

您可以将其设置为新的全局循环:

asyncio.set_event_loop(asyncio.new_event_loop())

然后再次使用 asyncio.get_event_loop()

或者,只需重新启动您的 Python 解释器,当您第一次尝试获取全局事件循环时,您会得到一个全新的、未关闭的。

从 Python 3.7 开始,创建、管理和关闭循环(以及一些其他资源)的过程在使用 asyncio.run() 时会为您处理。应该使用它来代替loop.run_until_complete(),并且不再需要先获取或设置循环。

在 Windows 上似乎是 EventLoopPolicy 的问题,使用此代码段解决它:

asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())

...以防万一:

import platform
if platform.system()=='Windows':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

如果您曾经在云中部署过代码,它可能会避免痛苦的调试。