Gplus E-mail
Home » Uncategorized » Gracefully closing Python sockets when developing

Gracefully closing Python sockets when developing

I thought I’d put this somewhere I can remember. Whenever I do anything involving socket programming, I inevitably make a mistake at some point and get stuck in an infinite loop or something or other. The problem is that unless everything worked the way it was supposed to, you can leave ports open until they timeout. Sure, this could be a security risk, but it’s really just annoying when you try to reconnect.

Perhaps there is a better way to handle this, but this is what I do. First thing I put in every Python script that declares a socket, I put this code at the top. This way, if I ever get stuck, I can signal the program with SIGINT (Ctrl + c) and the socket will be closed properly.


from signal import signal, SIGINT
def sigint_received(signum, frame):
 print "Exiting gracefully..."
# register SIGINT callback
signal(SIGINT, sigint_received)
© (c) Ryan E. Guerra 2000-2016