“Asyncio 事件循环已关闭"当得到循环 [英] "Asyncio Event Loop is Closed" when getting loop

查看:49
本文介绍了“Asyncio 事件循环已关闭"当得到循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

导入异步异步定义 hello_world():打印(你好世界!")loop = asyncio.get_event_loop()# hello_world() 协程完成时返回的阻塞调用loop.run_until_complete(hello_world())循环关闭()

我收到错误:

RuntimeError: 事件循环已关闭

我使用的是 python 3.5.3.

解决方案

在运行该示例代码之前,您已经在全局事件循环中调用了 loop.close():><预><代码>>>>导入异步>>>asyncio.get_event_loop().close()>>>asyncio.get_event_loop().is_closed()真的>>>asyncio.get_event_loop().run_until_complete(asyncio.sleep(1))回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中.文件/.../lib/python3.6/asyncio/base_events.py",第 443 行,在 run_until_complete 中self._check_closed()文件/.../lib/python3.6/asyncio/base_events.py",第 357 行,在 _check_closedraise RuntimeError('事件循环已关闭')运行时错误:事件循环已关闭

您需要创建一个循环:

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(),并且不再需要首先获取或设置循环.

When trying to run the asyncio hello world code example given in the docs:

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()

I get the error:

RuntimeError: Event loop is closed

I am using python 3.5.3.

解决方案

You have already called loop.close() before you ran that sample piece of code, on the global event loop:

>>> 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

You need to create a new loop:

loop = asyncio.new_event_loop()

You can set that as the new global loop with:

asyncio.set_event_loop(asyncio.new_event_loop())

and then just use asyncio.get_event_loop() again.

Alternatively, just restart your Python interpreter, the first time you try to get the global event loop you get a fresh new one, unclosed.

As of Python 3.7, the process of creating, managing, then closing the loop (as well as a few other resources) is handled for you when use asyncio.run(). It should be used instead of loop.run_until_complete(), and there is no need any more to first get or set the loop.

这篇关于“Asyncio 事件循环已关闭"当得到循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆