作者:北人南漂记 | 来源:互联网 | 2023-02-05 15:04
在从asyncio.get_event_loop()获取的循环上调用loop.close()之后的Python3.6.1中,是否可以创建一个新循环?
我已经查看了其他帖子,其中包含正确关闭循环的答案,以及如何使用task.cancel(),但是未能以某种方式使用这些示例,这样可以在第一次被关闭.我也尝试显式设置执行程序,然后调用executor.shutdown(wait = True),但这没有帮助.我也试过'del loop',并尝试了其他一些东西.
文档表明关闭一个事件循环是幂等的,不可逆转的.这是否意味着无法创建新循环?
这是一些简单的示例代码来演示这个问题:`
#!/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
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()
`
任何试图回答我的问题将不胜感激.
或者,创建一个事件循环,将它用于各种目的,然后在长时间运行的程序即将退出时关闭该循环是不好的形式?这似乎是错的.
1> dirn..:
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)