Stopping SocketServer on Python 2.5

David George dave at
Thu Mar 12 14:15:57 CET 2009

On 2009-03-12 08:03:06 +0000, "Mark Tolonen" <metolone+gmane at> said:

> "Falcolas" <garrickp at> wrote in message 
> news:1b6a95a4-5680-442e-8ad0-47aa9ea08344 at
>> On Mar 11, 1:11 pm, David George <d... at> wrote:
>>> Again, problem here is the issue of being unable to kill the server
>>> while it's waiting on a request. In theory, i could force it to
>>> continue by sending some sort of junk data with the method i use to
>>> stop the server, but that seems a bit hacky, don't you think?
>> Dave,
>> I agree, it does.
>> I'm in a bit over my head at this point, but does setting
>> self.socket.settimeout(0.5) cause the call to get_request (and thus
>> self.socket.accept()) to timeout? If so, that may be your ticket,
>> since socket.error exceptions are already caught by the TCPServer
>> class.
> Here's the relevant code from Python 2.6's  It uses 
> select() to see if a request is waiting to be serviced so 
> handle_request won't block.  If the poll interval expires the while 
> loop will check the __serving flag.  Not ideal, but better than 
> requiring a client to connect before the flag is checked.  The comment 
> lists another idea:
>    def serve_forever(self, poll_interval=0.5):
>         """Handle one request at a time until shutdown.
>         Polls for shutdown every poll_interval seconds. Ignores
>         self.timeout. If you need to do periodic tasks, do them in
>         another thread.
>         """
>         self.__serving = True
>         self.__is_shut_down.clear()
>         while self.__serving:
>             # XXX: Consider using another file descriptor or
>             # connecting to the socket to wake this up instead of
>             # polling. Polling reduces our responsiveness to a
>             # shutdown request and wastes cpu at all other times.
>             r, w, e =[self], [], [], poll_interval)
>             if r:
>                 self._handle_request_noblock()
>         self.__is_shut_down.set()
> -Mark

Thanks to everybody for helping me with this matter, but eventually 
i've had to settle for a simpler and probably far less elegant solution 
due to time constraints.

It seems that in 2.6 doesn't directly rely on anything 
that's in Python 2.6, so i've simply copied the code across and i'm 
using it in place of the version built into Python 2.5.

I will probably return to this at a later date and try for a more 
elegant solution, but right now university deadlines are looming!

Thanks all,


More information about the Python-list mailing list