Hey guys,

I'm fairly novice at Python so I hope my question isn't too mundane for you all.

I've been doing some research into creating Windows Services with Python and came across some useful information with regard to creating one. I've managed to register the service - my problem lies with getting the service to do anything constructive. For the time being, I'd simply like the service to write to a txt file every few seconds just so that I know the service is working (which is proving harder than it seems, so I suspect I may be missing out on something fairly obvious). To clarify, the service starts but then stops stating that there is no work to be done. Is there something wrong with the way that I'm trying to call my thread?

Any help or pointers would be greatly appreciated.

import LipcoEmailTool
import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
import os
import thread
import time

class aservice(win32serviceutil.ServiceFramework):
   
   _svc_name_ = "aservice"
   _svc_display_name_ = "Python Service"
   _svc_description_ = "Tests Python service"
   stopWork = 0
         
   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)
           styopWork = 1

   def DoWork():
      while 1:
         #write to a file
         time.sleep(2)
         a= open("test.txt", "w")
         a.write("This is a test")
         a.close()
                 
   def SvcDoRun(self):
     
      thread.start_new_thread(DoWork)
      self.timeout = 6000
    
      
def ctrlHandler(ctrlType):
   return True
                  
if __name__ == '__main__':   
   win32api.SetConsoleCtrlHandler(ctrlHandler, True)   
   win32serviceutil.HandleCommandLine(aservice)

Okay I managed to solve my problem - there were some fundamental errors with the way in which I setup my service.

For completeness' sake and the benefit of future posters, could you post the code here that solved your problem?

This article has been dead for over six months. Start a new discussion instead.