如何替换关闭的事件循环?

How do I replace a closed event loop?

我主要在 IPython 的互动 shell 中工作。有时我会从 Internet 上复制粘贴代码来测试它并使用示例。

如果我从 this tutorial 粘贴以下代码:

import asyncio

async def speak_async():  
    print('OMG asynchronicity!')

loop = asyncio.get_event_loop()  
loop.run_until_complete(speak_async())  
loop.close()  

我会关闭循环。 documentation 表示在事件循环关闭后不要在事件循环上使用任何方法。 async.get_event_loop() 仍然会 return 那个闭环。

不小心关闭了事件循环怎么办?我宁愿不重启解释器。

你可以 create and set a new event loop for the current context;

asyncio.set_event_loop(asyncio.new_event_loop())