2

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()
4
  • 2
    Where exactly is that while 1: code block? It looks like it is at top-level of the class. Is that legal? Can you check the indentation again and make sure that everything looks right? Commented May 17, 2012 at 0:15
  • have you tried specifying a path to the log file? i am not sure what directory a service "runs" in. Commented May 17, 2012 at 1:39
  • @andrewcooke Yes, I've tried it a few different ways even just making a call. For example, take out the file_pat= "test.py" and just put a print statement or the logging method. Commented May 18, 2012 at 16:03
  • @sarnold good catch, the indentation error that happened from posting it here, inside the code it's fine, and your right, it should be apart of the run Commented May 18, 2012 at 16:04

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.