The naïve pythoneer

More or less useful python rants?

2003-11-19

Signals and Python

It's not every day I feel the need to have signal handling in my python scripts, but I've found them useful in dealing with servers. Especially the kind of servers that serves forever..
The following code snipplet demonstrates the use of signals to gracefully exit a server that has been daemonized or simply put in the background.
import signal

def endHandler(signum,stackframe):
    raise KeyboardInterrupt

def main():
    try:
        server = Server('',8000)
        server.register_introspection_functions()
        server.register_instance(XMLRPCRegisters(conf_obj))
        try:
            signal.signal(signal.SIGTERM, endHandler)
            while 1:
                server.handle_request()
        except KeyboardInterrupt:
            pass
    finally:
        try:
            server.socket.close()
        except UnboundLocalError:
            """Since variables never got initialized -
            Die gracefully"""
            pass

(If you are using IE5.5/6.0 to view this page, the above text will not display correctly. Ask Bill to conform to the W3 standard.)

Now you can ask the server to terminate by issuing kill -15 $pid. This signal handler wil not catch kill -9, either way - should you have to use that chances are there's something else wrong with your server.
Was this helpfull or am I just ramblin'?
Back to work btw.

Comment on this post [ so far] ... more like this: [Pyhton signals]