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())