decorator and signal handler

Daniel Larsson daniel.j.larsson at gmail.com
Wed Sep 5 06:42:13 EDT 2007


On 9/5/07, stalex <shao.tu at gmail.com> wrote:
>
> Hi all,
>
> I wrote the following code since I want to try using a decorator to
> install signal handler:
>
> ## The test.py script
> #################
> import os
> import time
> import signal
>
> def sigHandler(sid):
>     def handler(f):
>         signal.signal(sid, f)
>         return f
>     return handler
>
> class Test(object):
>     @sigHandler(signal.SIGTERM)
>     def _sigHandler(self, signalId, currentFrame):
>         print "Received:", signalId
>
> if __name__ == "__main__":
>     print "pid:", os.getpid()
>
>     t = Test()
>     time.sleep(300)
>
> # From terminal, say A
> ####################
> $ python test.py
> pid: 1234
>
> # From terminal, say B
> ###################
> $ kill -TERM 1234
>
> After issuing the kill command from terminal B, the process of test.py
> from terminal A is terminated.
> Python print out some exception message as following:
> Traceback (most recent call last):
>     File "a.py", line 22, in <module>
>         time.sleep(300)
> TypeError: _sigHandler() takes exactly 3 arguments (2 given)
>
> At a guess, I think the decorator I defined did not pass the 'self' as
> the first argument to _sigHandler() method, did it? And I have no idea
> of how to write a correct one. Any suggestion?


You can't call an unbound method without supplying the instance explicitly.

Try decorate a global function instead, and it should work.

--
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070905/584829ea/attachment.html>


More information about the Python-list mailing list