asyncio 代码片段:获取运行中的事件循环或创建新循环
此 asyncio 代码片段展示如何获取运行中的事件循环,或在没有运行时创建新循环。
get_or_create_eventloop.py
import asyncio
def get_or_create_eventloop():
try:
return asyncio.get_event_loop()
except RuntimeError as ex:
if "There is no current event loop in thread" in str(ex):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return asyncio.get_event_loop()
else:
raise
# Usage example:
get_or_create_eventloop().create_task(asyncio.sleep(1))Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow