[Twisted-Python] Windows NT Service Problem
Lucas Taylor
lucas at lucaserve.com
Fri May 18 01:53:56 EDT 2007
Berkstresser, Dan wrote:
> Hello, I am trying to get my twisted project to run as a Windows
> Service. I have followed the instructions here:
> http://gradstein.info/DeployingTwistedWindows
> as well as here:
> http://svn.twistedmatrix.com/cvs/sandbox/moonfallen/?rev=18080#dirlist
This isn't really relevant to the references you've mentioned, but there
is a simple way to create Windows services with a minor amount of code
and it's not too onerous. You don't have to use py2exe, although it is
certainly possible to do so once you've got the rest working. I'm not
sure if this is the "best" way, but it has been successful for me in a
couple of projects over the past 2 years.
Below is a very simple example using the QOTD server from the core docs.
It doesn't use tac files, Application objects, or twistd, so it's very
basic. A "real" project will differ, but the basic mechanics of starting
and stopping the service are illustrated in the SvcDoRun() and
CheckForQuit() methods of the WindowsService object. The idea is to have
the reactor check for a Stop event periodically and exit if it is raised.
You should be able to install and remove it thusly:
python qotdservice.py install
python qotdservice.py remove
You can then test it out with the sample Echo client from the core docs.
"""qotdservice.py
Sample Twisted Windows Service
"""
# Service Utilities
import win32serviceutil
import win32service
import win32event
# Twisted imports
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
class QOTD(Protocol):
def connectionMade(self):
self.transport.write("An apple a day keeps the doctor away\r\n")
self.transport.loseConnection()
class WindowsService(win32serviceutil.ServiceFramework):
_svc_name_ = "TwistedWin32Service"
_svc_display_name_ = "Twisted Win32 Service"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
import servicemanager
self.CheckForQuit()
factory = Factory()
factory.protocol = QOTD
reactor.listenTCP(8007, factory)
reactor.run(installSignalHandlers=0)
def CheckForQuit(self):
retval = win32event.WaitForSingleObject(self.hWaitStop, 10)
if not retval == win32event.WAIT_TIMEOUT:
# Received Quit from Win32
reactor.stop()
reactor.callLater(1.0, self.CheckForQuit)
if __name__=='__main__':
win32serviceutil.HandleCommandLine(WindowsService)
More information about the Twisted-Python
mailing list