6

I have written a python script which will be installed in as windows service. Below is the code:

import datetime
import logging
from logging.handlers import RotatingFileHandler
import os
import time
from random import randint
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket


def setup_logger(logger_name, log_file, level=logging.ERROR):
    log_formatter = logging.Formatter('%(asctime)s %(message)s')
    my_handler = RotatingFileHandler(log_file, maxBytes=100 * 1024 * 1024, backupCount=5)
    my_handler.setFormatter(log_formatter)
    my_handler.setLevel(level)
    l = logging.getLogger(logger_name)
    l.handlers[:] = []
    l.addHandler(my_handler)


curr_path = os.getcwd()
log_file = "F:\\Projects\\TestService\\logs\\application.log"
setup_logger('debug', log_file)
log = logging.getLogger('debug')

class AppServerSvc(win32serviceutil.ServiceFramework):
    _svc_name_ = "test_service"
    _svc_display_name_ = "Test Service"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)
        self.isrunning = False

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.isrunning = False

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        self.isrunning = True
        self.main()

    def main(self):
        while self.isrunning:
            log.error("Running {}".format(randint(00, 99)))
            time.sleep(10)


if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)

I have run the command python test_service.py install to install the service and got the correct output Installing service test_service Service installed. When I open services tab I can see my service listed there. When I click on start service I am getting below error:

enter image description here

Can anyone please tell me what is wrong in the code due to which its not starting the service. Please help. Thanks

UPDATE:

I ran the service in debug mode in cmd and looks like it is working fine. But from the services tab, its not working and showing above error.

> python test_service.py debug
      Debugging service test_service - press Ctrl+C to stop.
      Info 0x40001002 - The test_service service has started.

When starting the service, it gives same error:

> python test_service.py start
     Starting service test_service
     Error starting service: The service did not respond to the start or control request in a timely fashion.

Not sure why its not running and in debug mode it runs fine. Please help.

4
  • Hi, have you seen this? Commented Sep 5, 2020 at 14:29
  • @CarloZanocco Yes have seen that and wrote all my code using that answer only. But anyways I have found the solution Commented Sep 5, 2020 at 14:34
  • Hi , Can you please share the solution, I am also facing similar problem? Commented May 18, 2021 at 10:26
  • @SriPallavi I have answered it Commented May 18, 2021 at 13:08

1 Answer 1

6

Anyone facing this issue, just copy pywintypes36.dll

from Python36\Lib\site-packages\pywin32_system32

to Python36\Lib\site-packages\win32

Helpful commands:

  1. Install a service: python app.py install

  2. Uninstall a service: python app.py remove

  3. Start a service: python app.py start

  4. Update service: python app.py update

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.