2010-11-18 61 views
1

我正在嘗試編寫一個爲Python編寫的twistd庫的應用程序。應用程序文件結束類似如下:在python中終止一個扭曲的應用程序

工廠= protocol.ServerFactory()

factory.protocol = EchoServer的

申請= service.Application( 「回波」)

internet.TCPServer( 8001,factory).setServiceParent(應用程序)

我想在我的appication終止前(例如關閉文件)運行某些操作。有誰知道這是怎麼做到的嗎?因爲這是一個事件處理程序,我不知道清理函數在哪裏被調用。

回答

1

您需要將代碼添加到ServicestartServicestopService方法中。

一種方法是這樣的:

from twisted.application import service 
from twisted.internet import protocol 

class MyService(service.Service): 
    def __init__(self,port=8001): 
    self.port = port 
    def startService(self): 
    self.factory = protocol.ServerFactory() 
    self.factory.protocol = EchoServer 
    from twisted.internet import reactor 
    reactor.callWhenRunning(self.startListening) 
    def startListening(self): 
    from twisted.internet import reactor 
    self.listener = reactor.listenTCP(self.port,self.factory) 
    print "Started listening" 
    def stopService(self): 
    self.listener.stopListening() 
    # Any other tidying 


application = service.Application("Echo") 
MyService().setServiceParent(application)