Ctrl+C sends EOFError once after cancelling process [duplicate]
So. You've found a pretty old Python bug. It's to do with the async nature of keyboard interrupts, AND how if you send a KeyboardInterrupt
to Python while hanging, and it doesn't respond to the interrupt, the second interrupt will raise the even stronger EOFError
. However, it seems, that these two collide, if you have an async KeyboardInterrupt
caught followed by an input with a second KeyboardInterrupt
, there will some stuff left in some buffer, which triggered EOFError
.
I know this isn't a great explanation, nor is it very clear. However, it allows for a pretty simple fix. Let the buffer to catch up with all the async interrupts, and than start waiting for an input:
import timedef parse(inp): time.sleep(1) print(inp) if inp == 'e': return 'exit'while True: try: user_in = input("> ").strip() except (KeyboardInterrupt, Exception) as e: print(e.__class__.__name__) continue if not user_in: continue try: if parse(user_in) == 'exit': break except KeyboardInterrupt: print("Cancelled") time.sleep(0.1) # This is the only line that's added
Now doing the same actions you did produces this:
> testCancelled>>>>> KeyboardInterrupt> KeyboardInterrupt> KeyboardInterrupt> KeyboardInterrupt> KeyboardInterrupt>> KeyboardInterrupt>>> KeyboardInterrupt> KeyboardInterrupt>