简体   繁体   English

如何在python守护程序的信号处理程序中调用类方法?

[英]How do you call class methods in a signal handler in python daemon?

I'm trying to write a signal handler that will call methods from a class variable. 我正在尝试编写一个信号处理程序,该处理程序将从类变量中调用方法。

I have code that looks like this: 我有看起来像这样的代码:

import daemon
class bar():
    def func():
         print "Hello World!\n"

def sigusr1_handler(signum,frame):
    foo.func() 

def main():
    foo = bar()

context = daemon.DaemonContext(stdout=sys.stdout)
context.signal_map = {
    signal.SIGUSR1: sigusr1_handler
}

with context:
    if (__name__="__main__"):
        main()

This doesn't work. 这行不通。 Python throws a NameError exception when I do a kill -USR1 on the daemon. 当我在守护程序上执行kill -USR1时,Python抛出NameError异常。 I also tried defining functions inside main that would handle the exception and call those functions from the signal handlers, but that didn't work either. 我还尝试在main内部定义函数,这些函数将处理异常并从信号处理程序中调用这些函数,但这也不起作用。

Anybody have ideas on how to implement this? 有人对如何实现这一点有想法吗?

One option would be to import class bar inside your sigusr1_handler function. 一种选择是将类栏导入到sigusr1_handler函数中。 It's probably a good idea to have it in a different file anyway 无论如何,将其保存在其他文件中可能是一个好主意

Do you import signal? 您导入信号吗? Because if I run you code I get: 因为如果我运行您的代码,我会得到:

Traceback (most recent call last):
  File "pydaemon.py", line 16, in <module>
    signal.SIGUSR1: sigusr1_handler
NameError: name 'signal' is not defined

You might fix this with: 您可以使用以下方法解决此问题:

import signal

And have a look at your string comparison oparator 看看你的字符串比较器

with context:
    if (__name__="__main__"):
        main()

I generally use the '==' operator instead of '=' 我通常使用'=='运算符而不是'='

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM