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

# 使用例:
get_or_create_eventloop().create_task(asyncio.sleep(1))

同じカテゴリの類似記事をチェック: Python