在python中终止一个扭曲的应用程序
问题描述:
我正在尝试编写一个为Python编写的twistd库的应用程序。应用程序文件结束类似如下:在python中终止一个扭曲的应用程序
工厂= protocol.ServerFactory()
factory.protocol = EchoServer的
申请= service.Application( “回波”)
internet.TCPServer( 8001,factory).setServiceParent(应用程序)
我想在我的appication终止前(例如关闭文件)运行某些操作。有谁知道这是怎么做到的吗?因为这是一个事件处理程序,我不知道清理函数在哪里被调用。
答
您需要将代码添加到Service
的startService
和stopService
方法中。
一种方法是这样的:
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)