[Python] Python asyncio: execute an asyncronous function while the main thread is blocked

Discussão em 'Python' iniciado por Stack, Julho 28, 2025.

  1. Stack

    Stack Membro Participativo

    I'm coding a python project split into two parts:

    1. a PySide6 GUI interface that needs to run on the main thread syncronously, and consequently block it,
    2. a playwrith virtual web browser (asyncronous),

    and I got a problem with the order of execution of asyncronous function.

    I came up with this code :

    async def run_app():
    global page_manager, gui_manager
    pw: Playwright | None = None

    try:
    # Those three following are quick and do not cause any significant time loss
    pw = await async_playwright().start()
    page_manager = PageManager(pw)
    gui_manager = GUIManager()

    # The `page_manager.init(settings.BROWSER)` should be starting about here

    gui_manager.init() # This is a prerequisit for the next line
    page_url, save_path = gui_manager.run_sync() # This blocks the main thread

    await page_manager.init(settings.BROWSER) # This function should be executed during the GUI
    await page_manager.run(page_url) # This is ran after the end of `gui_manager.run_sync()`
    except Exception as e:
    logger.critical(f"An error occurred (exiting) : {str(e)}")
    raise
    finally:
    gui_manager.close()
    await page_manager.close()
    if pw:
    await pw.stop()

    if __name__ == "__main__":
    asyncio.run(run_app())


    Currently, the program starts with the GUI and when the user did its selection, the playwrith instance is initialised then processed.

    However, I what the initialisation of the playwrith instance to occur while the GUI is running, so that no time is lost when the user did its selection. Initialising it before the GUI would not work either.

    I tried asyncio.to_thread, I tried tinkering the event loops which I dont understand fully, I tried create intermidiate function but none of those work, sometimes is raises an complex low-level error after the GUI exists and sometimes it simply initialised the page_manager after.

    If possible, I would like to not mix the threading library and the asyncio library.

    Thanks for your time.

    Continue reading...

Compartilhe esta Página