The following code just hangs without ever printing anything:
import asyncio
async def foo(loop):
print('foo')
loop.stop()
loop = asyncio.new_event_loop()
asyncio.ensure_future(foo(loop))
loop.run_forever()
If I use get_event_loop everything works fine. Is there something I'm doing wrong or have I stumbled upon a bug?
I'm using Python 3.5.1.
stop() – the stop function stops a running loop. is_running() – this function checks if the event loop is currently running or not. is_closed() – this function checks if the event loop is closed or not. close() – the close function closes the event loop.
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.
The alternative way of starting up your event loop is to call the run_forever() method which will subsequently start your asyncio based event loop and have it run indefinitely until the program comes to an end or the stop() method is called.
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.
asyncio.AbstractEventLoopPolicy.new_event_loop
documentation says:
If there’s need to set this loop as the event loop for the current context,
set_event_loop()
must be called explicitly.
import asyncio
async def foo(loop):
print('foo')
loop.stop()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop) # <----
asyncio.ensure_future(foo(loop))
loop.run_forever()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With