cx_Freeze icon indicating copy to clipboard operation
cx_Freeze copied to clipboard

“Error 1053: The service did not respond timely”, could not start Windows service created with cx_Freeze from Python code

Open Gim6626 opened this issue 6 years ago • 10 comments

I'm trying to create Windows service from my Python code using cx_Freeze. Python code works fine, it's debugged and reliable, but when I create exe file I got problems.

Here is my cx_Freeze setup code:

# Config file for packing python scripts into exe file
# Run with "python.exe create_win_exe.py build"
import sys
from cx_Freeze import setup, Executable

version = '1.00'

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {'packages': ['win32timezone'], 'includes': ['idna.idnadata']}

# Use default base - console application
base = None

setup(name = "service-test",
      version = version,
      description = "Service test",
      options = {"build_exe": build_exe_options},
      executables = [Executable("service-test.py", base=base)])

Python code (I've taken example from here https://stackoverflow.com/questions/32404/how-do-you-run-a-python-script-as-a-service-in-windows/32440#32440):

# -*- coding: utf-8 -*-
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import datetime
import time

class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService5"
    _svc_display_name_ = "Test Service 5"
    stop_flag = False

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

    def SvcStop(self):
        self.stop_flag = True
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

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

    def main(self):
        fout = open('C:\\Users\\Константин\\service-test.log', 'w')
        while not self.stop_flag:
            try:
                fout.write(str(datetime.datetime.now()) + '\n')
                fout.flush()
            except BaseException as be:
                print('Error while writing to file: {}'.format(str(be)))
            time.sleep(1)

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

When I create exe file, I could install it as service:

  > service-test.exe install
  Installing service TestService5
  Service installed

Also I could finely debug it, it works as expected.

But it doesn't start:

> service-test.exe start
Starting service TestService5
Error starting service: The service did not respond timely

Could anybody help with it? I've posted about it on https://stackoverflow.com/questions/53902729/error-1053-the-service-did-not-respond-timely-could-not-start-windows-servic , but I think it is cx_Freeze or something like that related cause Python code works fine and I could start bare Python coded service with no problems.

Gim6626 avatar Dec 25 '18 18:12 Gim6626

Hello,

I know this is a old ticket but I encountered the same issue today with cx_freeze 6.2 and python 3.7.4.

My application works well with when frozen as a console executable, but fails to start when frozen as windows service.

I have narrow down problem to numpy import.

You can reproduce the problem with the cx_Freeze service example by adding import numpy in ServiceHandler.py and using the following options in setup.py:

options = {
    "build_exe": {
        "includes": ["ServiceHandler"],
        "excludes": ["tkinter", "numpy.random._examples"]
    }
}

Environment:

$ python --version
Python 3.7.4
$ python -m pip freeze
cx-Freeze==6.2
numpy==1.19.2

pbesson-invn avatar Oct 06 '20 17:10 pbesson-invn

@pbesson-invn cx_Freeze 6.3 has just been released. Can you check if this has been resolved?

Can you use numpy==1.18.2 to test and report?

marcelotduarte avatar Oct 21 '20 18:10 marcelotduarte

Still got the same problem with:

$ python --version
Python 3.7.4
$ python -m pip freeze
cx-Freeze==6.3
cx-Logging==2.2
importlib-metadata==2.0.0
numpy==1.18.2
zipp==3.3.1

pbesson-invn avatar Oct 22 '20 09:10 pbesson-invn

Did you solve the issue regarding the application running as windows services? It works as a Windows console but then I can not install it as a Windows service.

Python 3.8.0

cx-Freeze==6.5.1
numpy==1.19.5
Flask==1.1.2    

flaskapp = Executable('win32_service.py',base='Console') #is not working with 'base=Win32Service

Do you have a working test as Win32Service ??

Since this is compiled as the console is not able to recognize the window service. image

Here is my test code. https://github.com/mvgarcia07/python-flask-as-window-service/blob/main/setup.py

mvgarcia07 avatar Jan 15 '21 23:01 mvgarcia07

@mvgarcia07 You can adapt your sample project like our sample: https://github.com/marcelotduarte/cx_Freeze/tree/master/cx_Freeze/samples/service

marcelotduarte avatar Jan 16 '21 00:01 marcelotduarte

Thank you @marcelotduarte for the reply!

I tried the sample but I having an error with the cx_logging. When I do 'pip install cx_Logging'

cx-Freeze==6.5.1 Python 3.8.0

    src/cx_Logging.c(6): fatal error C1083: Cannot open include file: 'cx_Logging.h': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.28.29333\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2

mvgarcia07 avatar Jan 16 '21 15:01 mvgarcia07

@mvgarcia07 cx_Logging hasn't wheels/binary for py38+ and has to be compiled. It needs a C compiler, or you can get a compiled wheel at https://www.lfd.uci.edu/~gohlke/pythonlibs/#cx_logging

marcelotduarte avatar Jan 16 '21 17:01 marcelotduarte

@marcelotduarte Thanks that solved the cx_Logging.h issue!

However, when I build the executable is not doing anything I am not familiar with threading is that a requirement? I already have a service handler working. I just need to build the working executable.

It is hard to troubleshoot because it creates the .exe but does not do anything.

So what I did was to create a template example for testing and I added a Readme with all the steps I took. here it is https://github.com/mvgarcia07/python-flask-as-window-service/tree/main/cx_Freeze_example

  • If I compile as a console it works but of course is not a windows service python setup_console.py build
  • If I tried as windows services it compiled but the .exe does not do anything python setup.py build

I also asked the community to see if they already have an example of working with flask if not definitely this could be a contribution :)

Thanks in advance!

mvgarcia07 avatar Jan 16 '21 20:01 mvgarcia07

What I am suggesting is that you use cx_Logging instead of pywin32. cx_Logging was developed by the same author as cx_Freeze, exactly to simplify this process and deal with these problems.

However, when I build the executable is not doing anything I am not familiar with threading is that a requirement?

threading.Event() is used instead of win32event.CreateEvent(None,0,0,None) If you mixup, problems arise.

It is hard to troubleshoot because it creates the .exe but does not do anything.

So when using cx_Logging, if you have any problems, the errors are recorded in a log and you can find out what went wrong.

marcelotduarte avatar Jan 16 '21 21:01 marcelotduarte

@mvgarcia07 See at #885

marcelotduarte avatar Jan 17 '21 21:01 marcelotduarte