this shows how to enable a SimpleXMLRPCServer to be cleanly killed (exited) by a client.
Python, 19 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from SimpleXMLRPCServer import * class MyServer(SimpleXMLRPCServer): def serve_forever(self): self.quit = 0 while not self.quit: self.handle_request() def kill(): server.quit = 1 return 1 server = MyServer(('127.0.0.1', 8000)) server.register_function(kill) server.serve_forever()
I couldn't find a simple solution to the problem of ending a Server remotely. So, I hope this gives a simple example of one way to do it.
Easier way. You could also express this as:
This saves you the hassle of subclassing SimpleXMLRPCServer.
return value. Brian Quinlan adds a nice enhancement to the original code. But don't forget to add a return statement to the kill function.
Handling signals better. The idea is good but doesn't seem to help me with handling signals like Ctrl+C in the console too well.
Below I have put a complete, standalone script that provides an alternative server that has built-in support to map signals to a clean shutdown and an exposable shutdown method if you want to allow that via XML-RPC.
There are pros/cons to using a subclass approach, but it may be useful for some...
Thank you for that, it works a charm, although there is a small typo, this line: while not self.finished: server.handle_request() should probably read while not self.finished: self.handle_request()