Creating and managing a Windows service (part 2)

This part of the recipe shows the python code needed to create (install) the Windows service. I didn't write most of this, I just found it somewhere on the internet. Credit due to the original author.
import sys
import win32service, win32serviceutil

from config import SERVICE_NAME, SERVICE_DISPLAY_NAME, SOFTWAREPATH
service_path = "%s\myservice.exe" % SOFTWAREPATH

def debug(msg):
    print msg
   
def removeSvc():
    debug('called removeSvc()')
    win32serviceutil.RemoveService(SERVICE_NAME)
    debug('...service was removed')
   
def installSvc():
    debug('installSvc()')
    hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
    debug('...opened svc manager')
    try:
        try:
            hs = win32service.CreateService(hscm,
                                            SERVICE_NAME,
                                            SERVICE_DISPLAY_NAME,
                                            win32service.SERVICE_ALL_ACCESS,         # desired access
                                            win32service.SERVICE_WIN32_OWN_PROCESS,  # service type
                                            win32service.SERVICE_DEMAND_START,
                                            win32service.SERVICE_ERROR_NORMAL,      # error control type
                                            service_path,
                                            None,
                                            0,
                                            None,
                                            None,
                                            None)
            debug('...installed service')
            win32service.CloseServiceHandle(hs)
        except:
            debug('...failed to install service')
            debug('...%s' % sys.exc_info()[0])
            debug('...%s' % sys.exc_info()[1])
    finally:
        debug('...closing service handle')
        win32service.CloseServiceHandle(hscm)
       
if __name__ == "__main__":
    installSvc()
    raw_input('Press <ENTER> to continue...')

To delete the service, use this code:

import sys
import win32service, win32serviceutil

from config import SERVICE_NAME, SERVICE_DISPLAY_NAME

def debug(msg):
    print msg

def removeSvc():
    debug('called removeSvc()')
    win32serviceutil.RemoveService(SERVICE_NAME)
    debug('...service was removed')

if __name__ == "__main__":
    removeSvc()
    raw_input('Press <ENTER> to continue...')

Next, how to start/stop/set startup for this service.

Comments