decorator and signal handler

Michele Simionato michele.simionato at gmail.com
Wed Sep 5 06:32:52 EDT 2007


On Sep 5, 11:39 am, stalex <shao... at gmail.com> wrote:
> Hi all,
>
> I wrote the following code since I want to try using a decorator to
> install signal handler:

I do have a decorator for exactly that purpose in my code. Here it is:

def on(sig):
    '''
    A factory of decorators for signal handlers. An example of usage
is

    @on(signal.SIGTERM)
    def termination(frame):
        print 'sent SIGTERM'
        raise SystemExit

    Code calling termination.signal() will send a SIGTERM signal to
the
    main thread, which in turns will call the termination handler,
which
    will print a message and raise SystemExit.
    '''
    def handler_decorator(handler):
        'Install the handler and add a .signal function attribute to
it'
        signal.signal(sig, lambda signum, frame : handler(frame))
        handler.signal = lambda : os.kill(os.getpid(), sig)
        return handler
    return handler_decorator

 Michele Simionato




More information about the Python-list mailing list