According to the source the BaseServer.shutdown() must be called from a different thread than the one the server is running on.
However I am trying to shut down the server with a specific value provided to the server in a web request.
The request handler obviously runs in this thread so it will still deadlock after I have done this:
httpd = BaseHTTPServer.HTTPServer(('', 80), MyHandler)
print("Starting server in thread")
threading.Thread(target=httpd.serve_forever).start()
How can I accomplish what I want? Must I set up a socket or pipe or something (please show me how to do this, if it is the solution), where the main thread can block and wait on the child thread to send a message, at which point it will be able to call shutdown()?
I am currently able to achieve some “kind of works” behavior by calling “httpd.socket.close()” from the request handler. This generates an [Errno 9] Bad file descriptor error and seems to terminate the process on Windows.
But this is clearly not the right way to go about this.
Update ca. Aug. 2013 I have eloped with node.js to fill the need for robust async I/O, but plenty of side projects (e.g. linear algebra research, various command line tool frontends) keep me coming back to python. Looking back on this question, BaseHTTPServer probably has little practical value comparatively to other options (like various microframeworks that Phil mentions).
threading.Event is useful for signalling other threads. e.g.,
You might use a Queue if you want to send data between threads.