在从asyncio.get_event_loop()获取的循环上调用loop.close()之后的Python3.6.1中,是否可以创建一个新循环?
我已经查看了其他帖子,其中包含正确关闭循环的答案,以及如何使用task.cancel(),但未能以某种方式使用任何这些示例在第一次关闭后创建循环。我也尝试显式设置执行程序,然后调用executor.shutdown(wait = True),但这没有用。我也尝试过“循环”和其他一些东西。
文档表明关闭一个事件循环是幂等的,不可逆转的。这是否意味着无法创建新循环?
以下是一些用于演示此问题的简单示例代码:
`
#!/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()
#!/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()
`
任何回答我的问题的尝试都将不胜感激。
或者,创建一个事件循环,将它用于各种目的,然后在长时间运行的程序即将退出时关闭该循环是不好的形式?这似乎是错的。
答案 0 :(得分:12)
asyncio.get_event_loop
返回当前循环。它不关注循环的状态。如果在关闭之后需要新循环,则可以使用asyncio.new_event_loop
。
请注意,获取新循环不会影响对get_event_loop
的后续调用。如果您希望返回新的循环而非原始循环(特别是因为您可能已关闭它),您需要自己致电asyncio.set_event_loop
。
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)