开发者

termination of a twistd application in python

I am trying to write an application with twistd library written for Python. The application file ends like the following:

factory = protocol.ServerFactory()

factory.protocol = EchoServer

application = service.Application("Echo")

internet.TCPServe开发者_运维知识库r(8001, factory).setServiceParent(application)

I want to run something before my appication terminates (e.g. close a file). Does anyone know how to do that? because this is an event-handler and I don't know where the clean-up function is called.


You need to add code to the startService and stopService methods of the Service.

One way would be something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜