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

使用pywin32的win32serviceutil创建Windows服务遇Error 1053求助

解决Windows服务启动Error 1053(服务未及时响应)的实用方案

我之前用pywin32写Windows服务的时候也踩过这个1053的坑,当时折腾了好半天,给你整理几个靠谱的排查和解决方向:

1. 先搞定启动超时问题

Windows对服务启动有30秒的硬性时间限制,如果你的服务启动逻辑里有耗时操作(比如加载大配置文件、发起网络请求),直接塞在SvcDoRun里肯定会触发超时。

  • 正确的做法是把业务逻辑放到单独的线程里,SvcDoRun只负责启动线程然后进入等待状态,示例代码如下:
import win32serviceutil
import win32service
import win32event
import threading
import time

class MyService(win32serviceutil.ServiceFramework):
    _svc_name_ = "MyService2"
    _svc_display_name_ = "My Test Service"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.is_running = True

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.is_running = False
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        # 把耗时业务丢到单独线程,别在这里卡着
        threading.Thread(target=self._run_business, daemon=True).start()
        # 等待停止信号,让服务保持存活状态
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

    def _run_business(self):
        while self.is_running:
            # 这里写你的业务代码
            print("Service is running...")
            time.sleep(1)

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

2. 检查Python环境的路径问题

服务是用系统账户运行的,很可能找不到你本地的Python环境:

  • 安装服务时一定要指定完整的Python路径,别用py命令(容易版本混淆),比如:
C:\Python36\python.exe C:\pytest\your_service_script.py install --startup auto
  • 确保你安装pywin32的Python版本和服务调用的版本是同一个(比如都是3.6.4)。

3. 加日志!定位到底哪里错了

服务启动失败时没有控制台输出,全靠日志才能找到问题根源:

  • 在服务初始化和启动的关键节点加日志写入本地文件,比如:
import logging

def setup_logger():
    logging.basicConfig(
        filename='C:\\pytest\\service_debug.log',
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s'
    )

class MyService(win32serviceutil.ServiceFramework):
    def __init__(self, args):
        setup_logger()
        logging.info("服务初始化完成")
        win32serviceutil.ServiceFramework.__init__(self, args)
        # 其他初始化代码

    def SvcDoRun(self):
        logging.info("开始启动服务...")
        # 启动逻辑

启动失败后打开日志文件,就能清楚看到是依赖缺失、文件权限还是代码报错导致的。

4. 检查服务账户的权限

默认服务用的是Local System账户,这个账户权限有限,可能访问不了你的业务文件或者网络:

  • 打开服务管理器(按Win+R输入services.msc),找到你的服务右键→属性→登录,切换到有足够权限的账户(比如管理员账户),输入密码后重启服务试试。

5. 确认pywin32和Python版本兼容

Python3.6.4比较老,一定要装对应的pywin32版本,不然容易出兼容性问题:

  • 先卸载现有版本,再装兼容的:
pip uninstall pywin32
pip install pywin32==223  # 这个版本和Python3.x兼容,亲测可用

内容的提问来源于stack exchange,提问作者alireza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:32:32