我正在尝试使用 cx_Freeze 从我的 Python 代码创建 Windows 服务。 Python 代码运行良好,经过调试且可靠,但是当我创建 exe 文件时出现问题。
这是我的 cx_Freeze 设置代码:
# 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 代码(我从这里的例子 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)
当我创建 exe 文件时,我可以将它安装为服务:
> service-test.exe install
Installing service TestService5
Service installed
我也可以很好地调试它,它按预期工作。
但它没有启动:
> service-test.exe start
Starting service TestService5
Error starting service: The service did not respond timely
如果我使用 pyinstaller
而不是 cx_Freeze
也会遇到同样的问题。
有人可以帮忙吗?
最佳答案
可能是权限问题。
查看您的代码,您没有指定服务将在其下运行的帐户,因此它是在“本地系统”下创建的。 https://learn.microsoft.com/en-us/windows/desktop/Services/localsystem-account
尝试指示用户通过安装命令行参数运行您的服务,或者您可以在安装服务后导航到服务对话框 (services.msc) 并修改登录。
关于python - "Error 1053: The service did not respond timely",无法从 Python 代码启动使用 cx_Freeze 创建的 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53902729/