Today, I had to check how my script runs on the Windows command prompt[1], when I noticed something weird. I was working on something similar to this, but this is enough to demonstrate the problem. Here's the code.
def bing():
try:
raw_input()
except KeyboardInterrupt:
print 'This is what actually happened here!'
try: # pardon me for those weird strings
bing() # as it's consistent with everything in the chat room (see below)
print 'Yoo hoo...'
except KeyboardInterrupt:
print 'Nothing happens here too!'
Here's the situation. When the script runs, it waits for the input and the user is supposed to press Ctrl+C to raise a KeyboardInterrupt
which would (should) be caught by the except
block within bing()
. So, this should be the actual output. And, this is what happens when I run it in my Ubuntu terminal and IDLE (on both Windows & Ubuntu).
This is what actually happened here!
Yoo hoo...
But, this doesn't go as expected on the Windows command prompt. I rather get a strange output.
This is what actually happened here! Nothing happens here too!
It looks like a single KeyboardInterrupt
propagates throughout the program and finally terminates it.
I tried everything I could do. First, I used a signal.signal
to handle the SIGINT
(which didn't work), and then I used handling function to raise an Exception
which I'd later catch (which didn't work either), and then things got more complicated than it used to be. So, I landed back to my good old try... catch
. Then, I went to the room for Pythonists.
@poke suggested that an EOFError
is raised when we press Ctrl+C. Then, @ZeroPiraeus said that EOFError
is raised when one presses Ctrl+Z and Enter.
That was helpful, which drove the discussion after a few minutes of fiddling around. Soon, everything became chaos! Some results were good, some were unexpected, and a few went haywire!
The conclusion was to stop using Windows and ask my friends to use the Terminal (I agree). I could however do a workaround by catching the EOFError
along with the KeyboardInterrupt
. While it feels lazy to press Ctrl+Z and Enter each time, that's not a big problem for me. But, this is an obsession for me.
On further research, I also noticed that there's no KeyboardInterrupt
raised on the CMD when I press Ctrl+C.
There's nothing at the bottom. So, what happens here anyway? Why does the KeyboardInterrupt
propagate? Is there any way (at all) to make the output consistent with the terminal?
[1]: I've always worked on the terminal, but today I needed to ensure that my script works on all platforms (especially because most of my friends are non-coders and just stick to Windows).