I believe the OP's intention is to disconnect the server from the request handler, and I think that the KeyboardInterrupt aspect of its code just confuses things.
Pressing ctrl-c from the shell where the server is running will be able to close it without doing anything special. You cannot press ctrl-c from another shell and expect it to work, and I think that this may be the reason this confusing code arises. There is no need to handle KeyboardInterrupt in handle() when trying to OP, or near serve_forever() , as suggested by others. If you do not, it works as expected.
The only trick here - and this is difficult - is telling the server to exit the handler without blocking.
As the OP explains and shows in its code, it uses a single-threaded server, so the user who suggested closing it in a "different thread" does not pay attention.
I dug up the SocketServer code and found that the BaseServer class, which BaseServer to work with the streaming mixins available in this module, actually makes it difficult to use with non-streaming servers using threading.Event around the loop in serve_forever .
So, I wrote a modified version of serve_forever for single-threaded servers, which allows you to disconnect the server from the request processor.
import SocketServer import socket import select class TCPServerV4(SocketServer.TCPServer): address_family = socket.AF_INET allow_reuse_address = True def __init__(self, server_address, RequestHandlerClass): SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass) self._shutdown_request = False def serve_forever(self, poll_interval=0.5): """provide an override that can be shutdown from a request handler. The threading code in the BaseSocketServer class prevented this from working even for a non-threaded blocking server. """ try: while not self._shutdown_request:
If you send the string 'shutdown' to the server, the server ends the serve_forever . You can use netcat to verify this:
printf "shutdown" | nc localhost 52000
chadrik Jan 29 '14 at 20:57 2014-01-29 20:57
source share