Event loop created by asyncio.new_event_loop hangs

余生颓废 提交于 2019-12-22 05:38:09

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/34470856/event-loop-created-by-asyncio-new-event-loop-hangs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!