Unable to create new event loop after calling loop.close asyncio.get_event_loop in Python3.6.1

In Python3.6.1, after calling loop.close () in a loop retrieved from asyncio.get_event_loop (), can I create a new loop?

I looked at other posts with answers to close the loop correctly, and also how to use task.cancel (), but could not use any of these examples so that a new loop was created after the first close. I also tried to explicitly set the executor and later call executor.shutdown (wait = True), but that didn't help. I also tried "del loop" as well as a bunch of other things.

The documentation indicates that closing the event loop is idempotent and irreversible. Does this mean that a new cycle cannot be created?

Here is an example of a simple example to demonstrate the problem: `

 #!/usr/bin/env python3.6 ''' To demonstrate an issue, the following code was adapted from: https://docs.python.org/3/library/asyncio-eventloop.html ''' import asyncio def hello_world(loop): print('Hello World') loop.stop() loop = asyncio.get_event_loop() loop.call_soon(hello_world, loop) loop.run_forever() # loop.close() ''' If the commented out loop.close() above is uncommented, the following code will fail with: Traceback (most recent call last): File "./aquestion.py", line 28, in <module> loopNew.call_soon(hello_world, loopNew) File "/Library/Frameworks/Python.framework/Versions/3.6/lib /python3.6/asyncio/base_events.py", line 573, in call_soon self._check_closed() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 357, in _check_closed raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed ''' loopNew = asyncio.get_event_loop() loopNew.call_soon(hello_world, loopNew) loopNew.run_forever() 

code> `

Any attempts to answer my question will be appreciated.

Alternatively, would it be a bad form to create an event loop, use it for a variety of purposes, and then just close this loop when a long running program is about to exit? It just seems wrong.

+5
source share
1 answer

asyncio.get_event_loop returns the current loop. He does not pay attention to the state of the cycle. If you need a new loop after closing it, you can use asyncio.new_event_loop .

Remember that getting a new loop will not affect subsequent calls to get_event_loop . If you want this new loop to return instead of the original (especially because you probably closed it), you need to call asyncio.set_event_loop yourself.

 import asyncio async def f(): await asyncio.sleep(0) loop = asyncio.get_event_loop() loop.run_until_complete(f()) loop.close() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) 
+12
source

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


All Articles