user1399840
user1399840

Reputation: 53

Python program as Windows Service

below is my code that I am trying to turn into a windows service. You'll see test.py as the call it makes and all this is a short script that writes into a log file (as a test).

The code is there to make it a windows service and it does that fine, but when I run it nothing writes into the log file. Help greatly appreciated. Below is the code:

import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
import os, sys, string, time

class aservice(win32serviceutil.ServiceFramework):

   _svc_name_ = "MyServiceShortName"
   _svc_display_name_ = "A python test"
   _svc_description_ = "Writing to a log"

   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      
      servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, '')) 

  self.timeout = 1000     #1 seconds
  # This is how long the service will wait to run / refresh itself (see script below)

  while 1:
     # Wait for service stop signal, if I timeout, loop again
     rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout)
     # Check to see if self.hWaitStop happened
     if rc == win32event.WAIT_OBJECT_0:
        # Stop signal encountered
        servicemanager.LogInfoMsg("SomeShortNameVersion - STOPPED!")  #For Event Log
        break
     else:

              #what to run
              try:
                       file_path = "test.py"
                       execfile(file_path)
              except:
                       pass
             #end of what to run


def ctrlHandler(ctrlType):
   return True

if __name__ == '__main__':   
   win32api.SetConsoleCtrlHandler(ctrlHandler, True)   
   win32serviceutil.HandleCommandLine(aservice)

Edit: Thought for the sake of it I'd include my test.py file's code, it has unnecessary imports but will get the job done if you run it alone.

import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
import os
logfile = open("log.txt", "a") #open file to log restart timestamp
logfile.write("\nthat's good!!!!")
logfile.close()

Upvotes: 2

Views: 7268

Answers (1)

user1399840
user1399840

Reputation: 53

Okay so I figured it out and would like to come back and post in case anyone else is dealing with this, all though this was a tad unique.

You have to specify your file path if you are within a windows service, duh... but it wasn't done and I pulled my hair out for no reason.

file_path = "test.py"

should have been

file_path = r"c:\users\...\test.py"

Be careful when using '\' for windows file paths. They must be escaped like '\\' or the string must be declared as raw string ('r'). Using the unix like slash '/' separators works also but may look odd for windows users.

Upvotes: 2

Related Questions