diff --git a/aiomysql/pool.py b/aiomysql/pool.py index eaaddbe0..a1f19ae7 100644 --- a/aiomysql/pool.py +++ b/aiomysql/pool.py @@ -267,4 +267,10 @@ async def __aenter__(self): async def __aexit__(self, exc_type, exc_val, exc_tb): self.close() - await self.wait_closed() + try: + await self.wait_closed() + except RuntimeError as e: + if "Event loop is closed" in str(e): + # Gracefully handle event loop shutdown during asyncio.run() + return + raise diff --git a/aiomysql/sa/engine.py b/aiomysql/sa/engine.py index 243e5001..38713d07 100644 --- a/aiomysql/sa/engine.py +++ b/aiomysql/sa/engine.py @@ -195,7 +195,13 @@ async def __aenter__(self): async def __aexit__(self, exc_type, exc_val, exc_tb): self.close() - await self.wait_closed() + try: + await self.wait_closed() + except RuntimeError as e: + if "Event loop is closed" in str(e): + # Gracefully handle event loop shutdown during asyncio.run() + return + raise _EngineContextManager = _PoolContextManager