This decorator simply sets the function as the signal handler for the signal given as its argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | # a decorator to wrap signal handlers
import signal
def signal_handler( signal_number ):
"""
A decorator to set the specified function as handler for a signal.
This function is the 'outer' decorator, called with only the (non-function)
arguments
"""
# create the 'real' decorator which takes only a function as an argument
def __decorator( function ):
signal.signal( signal_number, function )
return function
return __decorator
if __name__ == "__main__":
"""test the decorator"""
sigterm_received = False
@signal_handler(signal.SIGTERM)
def handle_sigterm(signum, frame):
"""handle sigterm for test"""
global sigterm_received
sigterm_received = True
assert not sigterm_received
# send ourselves sigterm
import os
import time
os.kill(os.getpid(), signal.SIGTERM)
time.sleep(0.1)
assert sigterm_received
print "OK"
|
This is an 'impure' decorator which is run only for its side effect. I like it for the same reason I like @staticmethod: it puts the action right on top of the function involved.