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?