Python Asyncio 事件循环已关闭
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45600579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Asyncio Event Loop is Closed
提问by TryingToTry
When trying to run the asyncio hello world code example given in the 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()
I get the error:
我收到错误:
RuntimeError: Event loop is closed
I am using python 3.5.3.
我正在使用 python 3.5.3。
回答by Martijn Pieters
You have already called loop.close()
before you ran that sample piece of code, on the global event loop:
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
You need to create a newloop:
您需要创建一个新循环:
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.
然后asyncio.get_event_loop()
再次使用。
Alternatively, just restart your Python interpreter, the first time you try to get the global event loop you get a fresh new one, unclosed.
或者,只需重新启动 Python 解释器,第一次尝试获取全局事件循环时,您会得到一个全新的未关闭的。