except block isn't catching exception

sohcahtoa82 at gmail.com sohcahtoa82 at gmail.com
Fri Aug 7 02:34:48 CEST 2015


I've run into strange behavior involving a blocking call to a socket accept() on the main thread and thread.interrupt_main() being called on a worker thread.  Here's my code:

# BEGIN exception_test.py
import socket
import thread
import threading
import time


def worker():
    time.sleep(2)
    print 'Interrupting main'
    thread.interrupt_main()
    print 'main interrupted!'

sock = socket.socket()
sock.bind(('127.0.0.1', 8080))
sock.settimeout(5)
sock.listen(0)

t = threading.Thread(target=worker)
t.start()

try:
    connection, _ = sock.accept()
except KeyboardInterrupt:
    print 'KeyboardInterrupt!'
except socket.timeout:
    print 'Socket timeout!'

print 'exiting'

# END exception_test.py

I would expect this output:

Interrupting main
main interrupted!
KeyboardInterrupt caught!
exiting

But instead, I'm seeing this:

Interrupting main
main interrupted!
Traceback (most recent call last):
  File "exception_test.py", line 23, in <module>
    connection, _ = sock.accept()
KeyboardInterrupt

Despite my "except KeyboardInterrupt", the KeyboardInterrupt forced by the thread.interrupt_main() in the worker thread isn't being caught.

Other things worth noting is that the exception takes about 3 seconds after the call to thread.interrupt_main().  It appears to not actually happen until the sock.accept() times out.  If the call to sock.settimeout(5) is removed, the KeyboardInterrupt never appears and flow is still blocked on the sock.accept().

My Python version is 2.7.3.  I know its out of date, but I don't really have a choice.


More information about the Python-list mailing list