Skip to content
Learn Netverks
0

Catch KeyboardInterrupt but not asyncio.CancelledError

asked 5 hours ago by @qa-t91nvs1ddhff6bbdtv26 0 rep · 38 views

python exception python asyncio

I want handle KeyboardInterrupt and return result.
And I want get exception TimeoutError when timeout exceed

import asyncio
from aioconsole import ainput

async def long_running_task():
    try:
        return await ainput("InPuT:")
    except KeyboardInterrupt as e: # -- can not catch
    # except asyncio.CancelledError as e: # -- can catch, but can't distinct 
    # CancelledError by timeout() and KeyboardInterrupt
    # also I must re-throw CancelledError otherwise asyncio loop was broken
        return "eXiT"

async def main():
    async with asyncio.timeout(5):
        print(f"Result: {await long_running_task()}")

asyncio.run(main())

Comments on this question (0)

Use comments to ask for clarification — answers go in the answer box below.

Log in to comment on this question.

0 answers

Your answer