Exception "In the thread" MainThread "there is no cycle of current events in the process of working on a new cycle

This is a simple test code and result.

import asyncio

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

if __name__ == '__main__':

    asyncio.set_event_loop(None)      # Clear the main loop.
    loop = asyncio.new_event_loop()   # Create a new loop.
    loop.run_until_complete(test())   # Run coroutine over the new loop

Traceback (most recent call last):
  File "test_test.py", line 11, in <module>
    loop.run_until_complete(test())
  File "/usr/lib/python3.5/asyncio/base_events.py", line 387, in run_until_complete
    return future.result()
  File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
    raise self._exception
  File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
    result = coro.send(None)
  File "test_test.py", line 5, in test
    await asyncio.sleep(1)
  File "/usr/lib/python3.5/asyncio/tasks.py", line 510, in sleep
    loop = events.get_event_loop()
  File "/usr/lib/python3.5/asyncio/events.py", line 632, in get_event_loop
    return get_event_loop_policy().get_event_loop()
  File "/usr/lib/python3.5/asyncio/events.py", line 578, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'MainThread'.

I run async def test()on new loopand expect that asyncio.sleep(1), nested test(), also uses new loop.

In contrast, it sleep()still has access to main loop, which I set as None.

I know that I can reinstall main loopas new loopwith asyncio.set_event_loop(loop)before the call run_until_complete(), and it will work without any exceptions.

However, I want to know that for asynciothis is normal, that main loopMust be installed and used for coroutines regardless of the cycle in which coroutines are executed.

+6
1

   , asyncio , , .

Python 3.6. , , asyncio.sleep(), , loop.call_later() , .

Python 3.6 ( 3.5.3, ), get_event_loop() , , , . .

-, :

(, call_soon API) .

+6

Source: https://habr.com/ru/post/1693144/


All Articles