Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event loop created by asyncio.new_event_loop hangs

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.

like image 226
Elektito Avatar asked Dec 26 '15 11:12

Elektito


People also ask

How do I close Asyncio event loop?

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.

How does the Asyncio event loop work?

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 start Asyncio event loop?

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?

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

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()
like image 183
falsetru Avatar answered Oct 12 '22 01:10

falsetru