Exception “ There is no current event loop in thread 'MainThread' ” while running over new loop

后端 未结 1 816
广开言路
广开言路 2021-01-05 01:54

The is the simple test code and the result.

import asyncio

async def test():
    await asyncio.sleep(1)

if __name__ == \'__main__\':

    asyncio.set_event         


        
1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-05 02:44

    I want to know it is normal for asyncio that main loop Must be set and is used for coroutines regardless of a loop over which coroutine is run.

    This used to be required prior to Python 3.6. The reason is that functions like asyncio.sleep() need an event loop to be able to use loop.call_later() to schedule a wake-up call to complete the future.

    As of Python 3.6 (or 3.5.3, which included a fix for the issue), when get_event_loop() is invoked from a coroutine driven by an event loop, it always returns the event loop that drives it. As a result, your code works correctly.

    The new behavior is not mentioned in the online documentation, but is in the docstring:

    When called from a coroutine or a callback (e.g. scheduled with call_soon or similar API), this function will always return the running event loop.

    0 讨论(0)
提交回复
热议问题