Christian01
Christian01

Reputation: 581

Python Service: Unexpected status SERVICE_STOPPED in response to START control

I want to a python script as service. There two python file telegraf_config_function.py for the logic and telegraf_config_service.py shown in the following:

import win32serviceutil
import win32service
import win32event
import servicemanager
import logging
import time
import sys
from telegraf_config_function import OPCDynamicInstances
#import threading   

logging.basicConfig(
                filename='C:\\PythonWindowsService.log',
                level=logging.INFO,
                format='%(asctime)s - %(levelname)s - %(message)s'
            )

class PythonWindowsService(win32serviceutil.ServiceFramework):
    _svc_name_ = "1_PythonWindowsService"
    _svc_display_name_ = "Python Windows Service Example"
    _svc_description_ = "This is a simple Python Windows Service example."

    def __init__(self, args):
        logging.info("Init Service...")
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.running = True

    def SvcStop(self):
        # Called when the service is asked to stop
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.running = False
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)

    def SvcDoRun(self):
        logging.info("DoRun Service...")
        self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
        # This is where the service runs when started
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        #self.start_main_thread()
        self.main()
        
    # def start_main_thread(self):
    #     self.main_thread = threading.Thread(target=self.main)
    #     self.main_thread.start()

    def main(self):
        
        try:
            logging.info("Service is starting...")
            loadPrepareConfig = OPCDynamicInstances()
            self.ReportServiceStatus(win32service.SERVICE_RUNNING)
            while self.running:
                logging.info("Service is running...")
                ### --- ###
                loadPrepareConfig.run()
                ### --- ###
                time.sleep(10)  # Simulate some work by sleeping for 10 seconds

            logging.info("Service is stopping...")
        except Exception as e:
            logging.error(f"Service encountered an error: {str(e)}")
        
if __name__ == '__main__':
    # import sys
    # if len(sys.argv) == 1:
    #     # To handle the service through Python executable path
    #     sys.argv.append('run')

    #win32serviceutil.HandleCommandLine(PythonWindowsService)
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(PythonWindowsService)
        logging.info("Execute Service...")
        servicemanager.StartServiceCtrlDispatcher()
    else:
        logging.info("Direct Service Execution...")
        win32serviceutil.HandleCommandLine(PythonWindowsService)

Steps I do

  1. Run the following command in the directory of the script:

pyinstaller --onefile --runtime-tmpdir=. --hidden-import win32timezone --name PythonWindowsService .\telegraf_config_service.py

  1. Then I run the following NSSM command:

nssm install PythonService_Exe C:\Users\<MyUserName>\Documents\Python Scripts\Telegraf_Configuration\dist\PythonWindowsService.exe

  1. Then I set the following parameters with admin privileges:

nssm set PythonService_Exe AppStdout "C:\Users\<MyUserName>\Documents\Python Scripts\Telegraf_Configuration\logs\service.log

nssm set PythonService_Exe AppStderr "C:\Users\<MyUserName>\Documents\Python Scripts\Telegraf_Configuration\logs\service-error.log

  1. At last, I start the service with nssm start PythonService_Exe (with admin privileges) and get the following output

PythonService_Exe: Unexpected status SERVICE_STOPPED in response to START control.

Unfortunately, the logs are empty.

What did I wrong? What can be error in coding or process?

If I start the service via Windows Services I got the following error:

enter image description here

Upvotes: 0

Views: 51

Answers (0)

Related Questions