erdewit/nest_asyncio

RuntimeError: Cannot close a running event loop

do-me opened this issue · 1 comments

do-me commented

I just installed nest_asyncio in my Ipython environment (using Jupyter Notebook) to get a basic example of an asynchronous function running.

import asyncio
import datetime
import nest_asyncio
nest_asyncio.apply()

async def display_date(loop):
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)


loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()

It works but how should I now close this function after execution?
Due to Ipython's main async loop, If I try to use loop.close() it doesn't work and throws an error:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-9-c73182512528> in <module>
     16 # Blocking call which returns when the display_date() coroutine is done
     17 loop.run_until_complete(display_date(loop))
---> 18 loop.close()

~\Anaconda3\lib\asyncio\selector_events.py in close(self)
     81     def close(self):
     82         if self.is_running():
---> 83             raise RuntimeError("Cannot close a running event loop")
     84         if self.is_closed():
     85             return

RuntimeError: Cannot close a running event loop

Tested on Windows 10, Python 3.7.5 and 3.9.1.

It is not really related to using nest_asyncio, but a loop should be stopped - loop.stop() - before being closed. It's not necessary to stop a loop though, and certainly must not be done when in Jupyter.