【问题标题】:How to run python-daemon with twisted如何使用 twisted 运行 python-daemon
【发布时间】:2016-07-20 10:53:58
【问题描述】:

我正在尝试使用 python-daemon 库运行一个守护进程。我也在使用 twisted 进行网络连接。

服务器非常简单:

class Echoer(pb.Root):
    def remote_echo(self, st):
        print 'echoing:', st
        return st

if __name__ == '__main__':
    serverfactory = pb.PBServerFactory(Echoer())
    reactor.listenTCP(8789, serverfactory)
    reactor.run()

同样应该是守护进程的客户端如下:

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/null'
        self.pidfile_path =  '/tmp/foo.pid'
        self.pidfile_timeout = 5

    def run(self):
        clientfactory = pb.PBClientFactory()
        reactor.connectTCP("localhost", 8789, clientfactory)
        d = clientfactory.getRootObject()
        d.addCallback(self.send_msg)
        reactor.run()

    def send_msg(self, result):
        d = result.callRemote("echo", "hello network")
        d.addCallback(self.get_msg)

    def get_msg(self, result):
        print "server echoed: ", result

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

当我以python test.py start 运行客户端时,守护进程已启动,但不知何故连接未建立。

但如果我将客户端的最后几行更改如下:

app = App()
app.run()

然后连接将正确建立并正常工作。但在这种情况下,它不再是守护进程。

我在这里缺少什么?我怎样才能实现它?

【问题讨论】:

    标签: python twisted daemon


    【解决方案1】:

    Twisted 已经内置了守护程序功能,因此您无需添加 python-daemon。两者之间可能有一些有趣的行为重叠可能会咬你。如您所见,一旦您获得了应用程序,就很容易在前台运行,就像您在上面所做的那样。将它作为守护进程运行也很容易;有关twistd 的更多信息,请参阅twistd descriptiontwistd man page,但基本上您只需添加几行样板文件并通过twistd 运行您的服务器。

    请参阅文章Running a Twisted Perspective Broker example with twistd,了解如何执行此操作的分步演练。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-29
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 1970-01-01
      • 2011-11-18
      相关资源
      最近更新 更多