KeyboardInterrupt catch does not shut down the socketserver

Gabriel Genellina gagsl-py2 at
Sun May 17 07:41:21 CEST 2009

En Sat, 16 May 2009 04:04:03 -0300, Igor Katson <descentspb at>  
> Gabriel Genellina wrote:
>> En Fri, 15 May 2009 09:04:05 -0300, Igor Katson escribió:
>>> Lawrence D'Oliveiro wrote:
>>>> In message <mailman.185.1242375959.8015.python-list at>, Igor  
>>>> Katson wrote:
>>>>> Lawrence D'Oliveiro wrote:
>>>>>> In message <mailman.183.1242371089.8015.python-list at>,  
>>>>>> Igor Katson wrote:
>>>>>>> I have problems in getting a SocketServer to shutdown.
>>> Shutdown implies closing the listening socket, doesn't it?
>> No (perhaps it should, but that is another issue). There is a
>> documentation bug; BaseServer.shutdown is documented as "Tells the
>> serve_forever() loop to stop and waits until it does." [1]
>> The docstring is much more explicit: """Stops the serve_forever loop.
>> Blocks until the loop has finished. This must be called while
>> serve_forever() is running in another thread, or it will deadlock."""
>> So, if you have a single-threaded server, *don't* use shutdown(). And,  
>> to orderly close the listening socket, use server_close() instead. Your

> Hmm. Gabriel, could you please show the same for the threaded version?  
> This one deadlocks:
> [code removed]

The shutdown method should *only* be called while serve_forever is  
running. If called after server_forever exited, shutdown() blocks forever.

 from SocketServer import TCPServer, BaseRequestHandler
 from threading import Thread

server = TCPServer(('localhost',1234), BaseRequestHandler)
run_thread = Thread(target=server.serve_forever)
     print "press ^C to exit"
     import time; time.sleep(30)
except KeyboardInterrupt:
     print "^C detected"
print "bye"

But, what are you after, exactly? I think I'd use the above code only in a  
GUI application with a background server.
There are other alternatives, like asyncore or Twisted.

Gabriel Genellina

More information about the Python-list mailing list