首页 文章

Asyncio事件循环已关闭

提问于
浏览
17

尝试运行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 .

1 回答

  • 35

    在全局事件循环上运行该示例代码之前,您已经调用了 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解释器,第一次尝试获取全局事件循环时,您将获得一个全新的,未闭合的 .

相关问题