You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python编写的Windows服务无法启动:启动请求超时报错

解决Windows Python服务启动超时问题

针对你遇到的服务能正常安装卸载但启动时报错Error starting service: The service did not respond to the start or control request in a timely fashion的问题,可按以下步骤排查解决:

1. 确保pywin32组件正确注册

pywin32需要注册服务相关的系统组件,直接pip安装后可能未完成注册,执行以下命令完成注册:

python -m pywin32_postinstall.py -install

执行后重启命令提示符,重新安装并启动服务。

2. 添加详细日志排查启动卡点

极简代码中无实际业务逻辑,但仍可能因环境问题导致启动失败,添加自定义日志文件追踪服务执行流程:
修改你的代码,在关键方法中添加日志输出:

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import logging

class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "TestService"
    _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)
        # 初始化日志
        logging.basicConfig(
            filename='C:\\TestService.log',
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s'
        )

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        logging.info("Service stopping...")
        win32event.SetEvent(self.hWaitStop)
        logging.info("Service stopped")

    def SvcDoRun(self):
        logging.info("Service starting...")
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_,''))
        logging.info("SvcDoRun executed, calling main...")
        self.main()

    def main(self):
        logging.info("Main method started")
        # 等待停止信号,避免服务立即退出
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
        logging.info("Main method exited")

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

启动服务后查看C:\TestService.log,确认服务执行到哪一步卡住,定位具体问题。

3. 调整PyInstaller打包参数

使用--onefile打包时,程序会解压到临时目录运行,可能存在权限或依赖缺失问题,尝试以下优化:

  • 禁用--onefile,使用文件夹模式打包:
pyinstaller --hiddenimport win32timezone --hiddenimport win32service --hiddenimport win32event --hiddenimport servicemanager .\main.py
  • 若坚持使用--onefile,添加--noupx参数避免UPX压缩导致的依赖问题:
pyinstaller --hiddenimport win32timezone --onefile --noupx .\main.py

打包后确保整个输出目录的权限允许Local System账户访问。

4. 检查系统事件日志

打开Windows事件查看器,依次展开Windows日志 > 应用程序,查找与TestService相关的错误日志,其中会包含更详细的报错信息(如缺失的依赖库、权限不足等),根据日志内容针对性解决。

5. 调整服务运行账户

默认服务使用Local System账户运行,若Python环境或打包文件所在路径存在权限限制,可修改服务运行账户为本地管理员:

  1. 打开服务控制台,找到Test Service
  2. 右键选择属性,切换到登录选项卡
  3. 选择此账户,输入本地管理员账户和密码,点击确定
  4. 重新启动服务

内容的提问来源于stack exchange,提问作者Lars Kakavandi-Nielsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 20:43:13