2

Running Python 2.7.6 in Windows 7.

I have a little script that opens a socket, sends some data down it and waits for the response. I am trying to get Ctrl-C to exit the script instantly if it gets stuck trying to connect (for example the server is not listening). If I spam Ctrl-C the script eventually exits but not through my try/except.

I was originally running this in PyCharm's Terminal but suspected the IDE might be messing up the Ctrl-C but I don't get any result in CMD either. Ctrl-Pause/Break does exit the script but I can't use that in PyCharm's Terminal.

Am I doing something wrong or is this just how sockets work?

import socket
import sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    print("Trying to connect...")
    s.connect(("192.168.0.100", 80))
    s.sendall("Hello world")
except KeyboardInterrupt:
    print("Interrupted, exiting.")
    s.close()
    sys.exit(1)

print("Waiting for response...")
data = s.recv(1024)
s.close()

print(data)
  • What platform are you on? – Kellen May 14 '18 at 10:17
  • @Kellen Presume you mean Python version and OS? 2.7.6 on Windows 7. – Reece Bennett May 14 '18 at 12:55
  • 1
    it looks like this is an issue with the [GIL](http://www.dabeaz.com/python/GIL.pdf). Python processes calling into C APIs can block the Python interpreter from processing the interrupt: [see this issue comment for more info](https://github.com/zeromq/pyzmq/issues/100#issuecomment-44305870). It looks like Ctrl+break might work better on Windows. – Kellen May 14 '18 at 13:04

0 Answers0