Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
kuku119 opened this issue Jan 20, 2025 · 1 comment

Comments

@kuku119
Copy link

kuku119 commented Jan 20, 2025

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:
@mxschmitt
Copy link
Member

How did you get the traceback?

When I'm running it I only get Exception ignored in atexit callback: <function _close_playwright at 0x100bab2e0>.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants