How to programmatically exit from wsgi's serve_forever() loop

Ian Kelly ian.g.kelly at gmail.com
Tue Dec 28 02:28:09 EST 2010


On 12/27/2010 6:05 PM, python at bdurham.com wrote:
> Is it possible to programmatically exit from the wsgiref's
> serve_forever() loop?
> I tried the following, all without success:
> httpd.server_close()
> httpd.shutdown()
> sys.exit(1)
> os._exit(1) (shouldn't this always abort an application?)
> raise KeyboardInterupt (Ctrl+Break from console works)


 >>> help(wsgiref.simple_server.WSGIServer.serve_forever)
Help on method serve_forever in module SocketServer:

serve_forever(self, poll_interval=0.5) unbound 
wsgiref.simple_server.WSGIServer method
     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.

 >>> help(wsgiref.simple_server.WSGIServer.shutdown)
Help on method shutdown in module SocketServer:

shutdown(self) unbound wsgiref.simple_server.WSGIServer method
     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.


Did you try:

 >>> import threading
 >>> threading.Thread(target=httpd.shutdown).start()

Cheers,
Ian




More information about the Python-list mailing list