Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Asyncio Event Loop is Closed" when getting loop

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.

like image 429
TryingToTry Avatar asked Aug 09 '17 21:08

TryingToTry


People also ask

How do I fix a closed event loop?

Runtime Error: Event Loop is closed Problem Usually, this error can be fixed by replacing the asyncio. run() command with the command asyncio. new_event_loop(). run_until_complete() .

What is event loop in Asyncio?

The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses. Application developers should typically use the high-level asyncio functions, such as asyncio.

How do I stop Asyncio from looping events?

Run an asyncio Event Loop run_until_complete(<some Future object>) – this function runs a given Future object, usually a coroutine defined by the async / await pattern, until it's complete. run_forever() – this function runs the loop forever. stop() – the stop function stops a running loop.

How many times should Asyncio run () be called?

It should be used as a main entry point for asyncio programs, and should ideally only be called once. New in version 3.7.


1 Answers

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.

like image 55
Martijn Pieters Avatar answered Oct 15 '22 05:10

Martijn Pieters