2016-07-20 23 views
0

我試圖運行使用python-daemon庫的守護進程。我也正在使用扭曲的網絡。如何以扭曲的形式運行python-daemon

的服務器是非常簡單的:

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() 

然後連接將被正確建立和工作。但在這種情況下,它不再是守護進程。

缺少什麼我在這裏?我怎樣才能實現它?

回答

1

Twisted具有已內置的守護程序功能,因此您不需要添加python-daemon。兩者之間可能存在一些有趣的行爲重疊,可能會讓你咬牙切齒。正如您所看到的,一旦您獲得了應用程序,就可以像前面所做的那樣在前臺運行它。將它作爲守護進程運行也很容易;有關twistd的更多信息,請參閱twistd descriptiontwistd man page,但基本上,您只需添加幾行樣板並通過twistd運行服務器。

請參閱文章Running a Twisted Perspective Broker example with twistd瞭解如何執行此操作的分步演練。