“RuntimeError: This event loop is already running”; debugging aiohttp, asyncio and IDE “spyder3” in python 3.6.5

后端 未结 4 935
醉梦人生
醉梦人生 2021-02-15 12:29

I\'m struggling to understand why I am getting the \"RuntimeError: This event loop is already running\" runtime error. I have tried to run snippets of code from \"https://aiohtt

4条回答
  •  时光取名叫无心
    2021-02-15 13:03

    Looks to me Spyder runs its own event loop. You cannot run two event loops in a single thread.

    asyncio.run(coro, *, debug=False)

    This function cannot be called when another asyncio event loop is running in the same thread.

    This is what worked for me. I start my own loop if there is not other running loop:

    import asyncio
    
    async def say_after(delay, what):
        await asyncio.sleep(delay)
        print(what)
    
    async def main():
        await say_after(2, 'done')
    
    await say_after(1, 'ahoy')    
    
    loop = asyncio.get_event_loop()
    print(loop) # <_WindowsSelectorEventLoop running=True closed=False debug=False>
    if loop.is_running() == False:
        asyncio.run(main())
    else:
        await main()
    

提交回复
热议问题