ASYNCIO事件环路闭合
问题描述:
当试图运行在文档中给出的ASYNCIO的hello world代码示例:ASYNCIO事件环路闭合
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解释器,第一次尝试获取全局事件循环时,您会得到一个全新的新的未关闭的事件循环。