Windows Service with Python

I used this script to run a conversion service with Python on Windows. I stripped it down, so that others can use it for their needs.

Install the script from the windows shell:

>>python WindowsService.py install

And start it by:

>>python WindowsService.py start

import win32serviceutil
import win32evtlogutil
import win32event
import win32service
import win32com.client
import pywintypes
import os
import time
import sys
import pythoncom
from datetime import datetime
import string
import win32gui

class WindowsService(win32serviceutil.ServiceFramework):

    _svc_name_ ="WindowsService"
    _svc_display_name_ = "Service short desc"
    _svc_description_ = "Service long desc"

    def __init__(self, args):

        # Service Implementation

        win32serviceutil.ServiceFramework.__init__(self, args)
        #self.stopevent = threading.Event()
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.overlapped = pywintypes.OVERLAPPED()
        self.overlapped.hEvent = win32event.CreateEvent(None,0,0,None)

        # Start COM application here

        self.ReportServiceStatus(win32service.SERVICE_START_PENDING)

        self.globalServerRoot = [self.ret,self.serverRoot,int(self.serverPort)]

    def SvcDoRun(self):

        import servicemanager
        # Start and write to eventlog
        interval = 1000 # loop interval 1000 milliseconds
        self.ReportServiceStatus(win32service.SERVICE_RUNNING)
        while True:

            # do something interesting here

        win32evtlogutil.ReportEvent(self._svc_display_name_,servicemanager.PYS_SERVICE_STOPPED,0,servicemanager.EVENTLOG_INFORMATION_TYPE,(self._svc_name_, ""))

    def SvcStop(self):

        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)

        # Do stop-actions with application here


        # report to SCM, that application is beeing stopped

        self.ReportServiceStatus(win32service.SERVICE_STOPPED)
        win32event.SetEvent(self.hWaitStop)

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(WindowsService)

Leave a Reply

Your email address will not be published. Required fields are marked *