2

我有一个使用旧版本的 python-daemon 创建的基本 Python 守护程序和以下代码:

import time
from daemon import runner

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/foo.pid'
        self.pidfile_timeout = 5
    def run(self):
        while True:
            print("Howdy!  Gig'em!  Whoop!")
            time.sleep(10)

app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

现在一切正常,但我需要在我的守护进程中再添加一个可能的命令。当前的默认命令是“启动、停止、重新启动”。我需要第四个命令“mycommand”,它只会在执行时运行此代码:

my_function()
print "Function was successfully run!"

我尝试过谷歌搜索和研究,但我自己无法弄清楚。我尝试手动获取参数而不陷入 python-daemon 代码,sys.argv但无法使其工作。

4

1 回答 1

0

查看 runner 模块的代码,以下应该可以工作......我在定义标准输出和标准错误时遇到问题......你能测试一下吗?

from daemon import runner
import time

# Inerith from the DaemonRunner class to create a personal runner
class MyRunner(runner.DaemonRunner):

    def __init__(self, *args, **kwd):
        super().__init__(*args, **kwd)

    # define the function that execute your stuff...
    def _mycommand(self):
        print('execute my command')

    # tell to the class how to reach that function
    action_funcs = runner.DaemonRunner.action_funcs
    action_funcs['mycommand'] = _mycommand


class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/foo.pid'
        self.pidfile_timeout = 5
    def run(self):
        while True:
            print("Howdy!  Gig'em!  Whoop!")
            time.sleep(10)

app = App()
# bind to your "MyRunner" instead of the generic one
daemon_runner = MyRunner(app)
daemon_runner.do_action()
于 2016-09-19T20:58:15.230 回答