[Python] Python interpreter freezing while handling exceptions with asyncio.to_thread

Discussão em 'Python' iniciado por Stack, Maio 14, 2025.

  1. Stack

    Stack Membro Participativo

    This is an abstracted version of my code - I'm actually using socket.accept, not time.sleep (the same things happen though). It happens in Python 3.11.9 (Windows)

    I want to use non-async function as async function, so I used asyncio.to_thread. But when an exception occured in non-async function (e.g. KeyboardInterrupt), the python interpreter just freezes and does not respond (and nothing was printed in console).

    import asyncio
    import time


    async def func_1():
    while True:
    print('print something..')
    await asyncio.sleep(0.5)

    async def func_2():
    print('start here')
    # await asyncio.sleep(100)
    await asyncio.to_thread(time.sleep, 100)
    print('end here')

    async def main():
    asyncio.create_task(func_1())
    await func_2()

    try:
    asyncio.run(main())
    except BaseException:
    print('exception has occured')


    I wonder why this happens, and how to fix it concisely.

    Continue reading...

Compartilhe esta Página