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

基于pywin32的Python Windows Service调试正常但安装后启动失败

解决Windows服务运行WebSocket回显服务器的启动错误

问题现象

开发了基于pywin32的WebSocket回显服务器,调试模式下执行python server.py debug可正常运行,客户端能接收回显消息。但以管理员权限执行python server.py install安装服务后,启动服务时报错:

本地计算机上的Python Echo WebSocket Server服务无法启动。有关更多信息......错误代码536870913。

环境信息:

  • Python版本:3.10.4
  • 操作系统:Windows 11

错误原因分析

错误代码536870913对应0x20000001,核心问题包括:

  • Windows服务运行环境与普通控制台程序存在差异,asyncio.run()无法在服务上下文里正确初始化事件循环
  • 当前代码未处理服务停止时的asyncio任务终止逻辑,导致服务启动后无法响应控制信号
  • 服务默认工作目录可能并非程序所在目录,引发依赖加载异常

修复步骤及代码修改

1. 适配asyncio事件循环的服务运行环境

替换asyncio.run()为显式创建事件循环的方式,适配Windows服务上下文;同时实现服务停止时的优雅退出逻辑,终止事件循环。

修改后的server.py代码

import asyncio
import websockets
from SMWinservice import SMWinservice

DOMAIN = 'localhost'
PORT = 8765  # 替换为实际使用的端口号


class EchoServerService(SMWinservice):
    _svc_name_ = "EchoWSService"
    _svc_display_name_ = "Python Echo WebSocket Server"
    _svc_description_ = "A python written service of a WebSocket Echo Server running in localhost:8765"

    def start(self):
        self.isrunning = True
        # 显式初始化事件循环
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)
        # 创建停止信号事件
        self.stop_event = asyncio.Event()

    def stop(self):
        self.isrunning = False
        # 触发停止信号,终止异步任务
        if hasattr(self, 'stop_event'):
            self.stop_event.set()
        # 停止事件循环
        if hasattr(self, 'loop'):
            self.loop.call_soon_threadsafe(self.loop.stop)

    def process_message(self, message):
        print(message)
        return message

    async def handle(self, ws_client):
        async for message in ws_client:
            result = self.process_message(message)
            await ws_client.send(result)

    async def async_main(self):
        async with websockets.serve(self.handle, DOMAIN, PORT):
            # 等待停止信号
            await self.stop_event.wait()

    def main(self):
        if self.isrunning:
            try:
                self.loop.run_until_complete(self.async_main())
            finally:
                self.loop.close()


if __name__ == '__main__':
    EchoServerService.parse_command_line()

2. 配置服务运行权限与工作目录

  1. 打开Windows服务管理器,找到Python Echo WebSocket Server服务,右键选择「属性」
  2. 「登录」标签页:选择本地系统账户,勾选「允许服务与桌面交互」(方便调试)
  3. 「恢复」标签页:设置第一次失败时的操作为「重新启动服务」

3. 重新部署服务

  1. 卸载旧服务:python server.py remove
  2. 重新安装服务:python server.py install
  3. 启动服务:python server.py start 或通过服务管理器启动

额外调试方案

若问题仍存在,可通过事件查看器获取详细错误:

  • 按下Win+R输入eventvwr.msc打开事件查看器
  • 展开「Windows日志」→「应用程序」,查找来源为Python Service的错误日志,获取具体异常信息

内容的提问来源于stack exchange,提问作者Oliver Mohr Bonometti

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:23:16