[Bug]: RuntimeError: Event loop is closed when using atexit to close async_playwright #2718
Open
Description
Version
1.49.1
Steps to reproduce
# browser_utils.py
import asyncio
import atexit
from typing import Optional
from playwright.async_api import async_playwright, Playwright, BrowserContext
_lock = asyncio.Lock()
_pwr: Optional[Playwright] = None
_context: Optional[BrowserContext] = None
async def start_playwright_persistent_context():
global _pwr
global _context
print('starting...')
async with _lock:
if (_pwr is None) != (_context is None):
raise RuntimeError
if _context is None:
_pwr = await async_playwright().start()
_context = await _pwr.chromium.launch_persistent_context('Chromium/User Data', executable_path='Chromium/chrome-win/chrome.exe')
return _context
start_browser = start_playwright_persistent_context
def _close_playwright():
global _pwr
global _context
print('closing...')
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
if _context is not None:
loop.run_until_complete(_context.close())
if _pwr is not None:
loop.run_until_complete(_pwr.stop())
atexit.register(_close_playwright)
if __name__ == '__main__':
async def main():
browser = await start_browser()
page = await browser.new_page()
await page.goto('http://localhost:8000')
print(await page.content())
asyncio.run(main())
Expected behavior
atexit can correctly close the Playwright instance.
Actual behavior
Additional context
No response
Environment
- Operating System: [Windows 10]
- CPU: [arm64]
- Browser: [Chromium]
- Python Version: [3.13.1]
- Other info:
Metadata
Assignees
Labels
No labels