Event loop created by asyncio.new_event_loop hangs

Elektito picture Elektito · Dec 26, 2015 · Viewed 8.4k times · Source

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.

Answer

falsetru picture falsetru · Dec 26, 2015

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()