Friday, February 6, 2009

Playing with signals in Python

A Python program is able to catch signals and handle them with the signal module. This is especially useful when you want to clean up after your program exits for any reason. This can be done with signal.signal, which sets a callback function for signal handlers.

This code will set an "alarm" that must be set every 30 seconds, or else a signal will be called to shut down the program (sort of a "watchdog" program).


def alarm_handler(signum, frame):
print "30 seconds have passed!"

signal.signal(signal.SIGALRM, alarm_handler)

signal.alarm(30)

while True:
data = raw_input("Write something in the next 30 seconds please: ")
signal.alarm(30)


Another use of signals would be to brutally terminate your program, since sometimes Python can hang on I/O, or a Thread object that is running (for some reason a Ctrl+C doesn't kill a program running a python thread):


import os, signal

# Brutally terminate this process
os.kill(0, signal.SIGTERM)

No comments: