Skip to content

[Bug]: RuntimeError: Event loop is closed when using atexit to close async_playwright #2718

Closed
@kuku119

Description

@kuku119

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

traceback.txt

Additional context

No response

Environment

- Operating System: [Windows 10]
- CPU: [arm64]
- Browser: [Chromium]
- Python Version: [3.13.1]
- Other info:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions