2

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 How do you run a Python script as a service in Windows?):

# -*- 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

Same trouble if I use pyinstaller instead of cx_Freeze.

Could anybody help with it?

Dmitriy Vinokurov
  • 365
  • 1
  • 6
  • 28

2 Answers2

1

Might be permissions issue.

Looking at your code, you do not specify the account the service will be run under, so it is created under "Local System". https://learn.microsoft.com/en-us/windows/desktop/Services/localsystem-account

Try indicating the user to run your service via the install command line arguments, or you can navigate to the services dialog (services.msc) after you've installed the service and modify the Log On.

0

I created a folder and placed two files into it: file.py and create_win_exe.py (file names not very important) And I used the following command: pyinstaller file.py in that same directory and it ran through the install process fine. Once it was finished, I navigated into the dist/file/ directory and opened file.exe, and it worked perfectly fine. I'm not sure why you have an error, but try using pyinstaller exactly how I've shown and see if it works.