KeyboardInterrupt Exception works sometimes?

2.1k views Asked by At

I have this simple python script:

import socket
import sys

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp"))
except socket.error as msg:
    print("Could not open socket connection!")
    print(msg)
    sys.exit(1)
try:
    s.bind(("", 0))
    print("Starting the listener...")
    while True:
        buff = s.recvfrom(65535)
        print(buff[1][0])
except KeyboardInterrupt:
    s.close()
    print("\nManually quitting...")
    sys.exit(3)
except socket.error as msg:
    s.close()
    print("Socket connection failed!")
    print(msg)
    sys.exit(2)
except:
    print("Something went wrong! Quitting...")
    sys.exit(4)
s.close()

When I run the script with Python 3.2.3, the Ctrl-C keyboard exception is not caught all the time, which means works sometimes. In fact the error message is different when trying to Ctrl-C from the program at arbitrary moment. Here is the output on the console when the script was ran 3 times right after another:

$ sudo python3 listener.py 
Starting the listener...
^CTraceback (most recent call last):
  File "listener.py", line 14, in <module>
    buff = s.recvfrom(65535)
KeyboardInterrupt

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "listener.py", line 17, in <module>
    s.close()
  File "/usr/lib/python3.2/socket.py", line 194, in close
    def close(self):
KeyboardInterrupt


$ sudo python3 listener.py 
Starting the listener...
^CTraceback (most recent call last):
  File "listener.py", line 14, in <module>
    buff = s.recvfrom(65535)
KeyboardInterrupt

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "listener.py", line 14, in <module>
    buff = s.recvfrom(65535)
KeyboardInterrupt


$ sudo python3 listener.py 
Starting the listener...
^C
Manually quitting...

It worked the last time. How come it only works sometimes!? What am I doing wrong?

1

There are 1 answers

0
Ethan Furman On

If you examine the stack trace carefully you will notice that there are two exceptions being dealt with:

Traceback (most recent call last):
  File "listener.py", line 14, in <module>

One on line 14 (in the try block); and the next one either again on line 14 or on line 17 (which is in the "Manually quiting" block).

It looks to me like you have a hardware problem with your keyboard and it sometimes sends two <ctrl-c>s instead of just one.