此 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))