Currently I’m working on a small MRCPv2 client written in Python, which is part of a bigger project at my laboratory. The client is started remotely by a program which controls and monitors several applications in the whole network and is stopped by it again.
In the Linux world catching “kill events” would be a simple task, to shut down another program a process just has to send a SIGTERM signal which can be caught be Python easily using the signal module which comes with every Python installation. However, on Windows things are a little bit harder, because the operating system never produces SIGTERM (and SIGILL) events according to the signal.h documentation from MSDN. That’s why it took me some time to figure out how to catch “kill” events under Windows with Python.
First of all, there are two different ways to close a program in Windows using the .NET API. The first one is to use Process.Kill which is the Microsoft version of SIGKILL and there is Process.CloseMainWindow which works similar to SIGTERM. To catch the latter one with Python you have to install the pywin32 library and define a handler by using win32api.SetControlCtrlHandler.
Here is a small example how to install an “exit handler” under Linux or Windows:
import os, sys def set_exit_handler(func): if os.name == "nt": try: import win32api win32api.SetConsoleCtrlHandler(func, True) except ImportError: version = “.”.join(map(str, sys.version_info[:2])) raise Exception(”pywin32 not installed for Python ” + version) else: import signal signal.signal(signal.SIGTERM, func)
Use it like this:
if __name__ == "__main__": def on_exit(sig, func=None): print "exit handler triggered" import time time.sleep(5) set_exit_handler(on_exit) print "Press to quit" raw_input() print "quit!"
Edit: I’ve cleaned up the code, this version should work with Python 2.4 and 2.6, I didn’t tried it with Python 3000 yet.