MeWrite Docs

Python: RuntimeError - Event loop is closed

Pythonのasyncioでイベントループが閉じている場合のエラー原因と解決策

概要

asyncioのイベントループが閉じた後に非同期操作を実行しようとした際に発生するエラーです。

エラーメッセージ

``` RuntimeError: Event loop is closed ```

原因

  1. ループ終了後の操作: asyncio.run()後にawait
  2. Windows固有の問題: ProactorEventLoopの問題
  3. 複数ループの競合: 異なるスレッドでのループ使用
  4. リソースクリーンアップ時: aiohttp等のセッション終了時

解決策

1. asyncio.run()を正しく使用

```python import asyncio

async def main(): await some_async_function() await another_async_function()

全ての非同期処理をmain()内で完結

asyncio.run(main()) ```

2. Windows環境での対策

```python import asyncio import sys

if sys.platform == ‘win32’: asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

asyncio.run(main()) ```

3. aiohttpセッションの適切な終了

```python import aiohttp

async def main(): async with aiohttp.ClientSession() as session: async with session.get(‘https://example.com’) as response: return await response.text()

または明示的にクローズ

async def main(): session = aiohttp.ClientSession() try: async with session.get(‘https://example.com’) as response: return await response.text() finally: await session.close() ```

4. 既存ループを再利用

```python import asyncio

def get_or_create_eventloop(): try: return asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop

loop = get_or_create_eventloop() result = loop.run_until_complete(main()) ```

よくある間違い

  • Jupyter Notebookで asyncio.run() を使用
  • グローバルセッションを閉じ忘れ
  • スレッド間でループを共有

関連エラー

関連エラー

Python の他のエラー

最終更新: 2025-12-10