Asyncio事件循环已关闭

时间:2017-08-09 21:01:46

标签: python python-asyncio

尝试运行docs中给出的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。

2 个答案:

答案 0 :(得分:43)

在全局事件循环中运行该示例代码之前,您已调用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

您需要创建一个 new 循环:

loop = asyncio.new_event_loop()

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

asyncio.set_event_loop(asyncio.new_event_loop())

然后再次使用asyncio.get_event_loop()

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

答案 1 :(得分:17)

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

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