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

Python win32serviceutil服务启动失败:ModuleNotFoundError求助

Python Windows服务启动失败:ModuleNotFoundError解决方案

问题描述

基于win32serviceutil创建了PowerMasterUPS Windows服务,服务安装过程正常:

C:\›python PowerMasterUPS.py install
Installing service PowerMasterUPS
copying host exe 'C:\Users\x\AppData\Local\Programs\Python\Python311\Lib\site-packa
C:\Users\x\AppData\Local\Programs\Python311\pythonservice.exe'
Service installed

但启动服务或执行调试命令时失败,报错信息如下:

C:\›python PowerMasterUPS.py debug
Debugging service PowerMasterUPS - press Ctrl+C to stop.
Error (xC0000004 - Python could not import the service's module

ModuleNotFoundError: No module named 'PowerMasterUPS'

(null): (null)

已尝试手动添加sys.path.append("C:\\")(脚本所在目录),但问题未解决,相关代码如下:

import socket
import win32serviceutil
import servicemanager
import win32event
import win32service
import requests ,time ,json, os, sys
sys.path.append("C:\\")

class SMWinservice(win32serviceutil.ServiceFramework):
    '''
    SMWinservice
    by Davide Mastromatteo
    '''

    _svc_name_ = 'pythonService'
    _svc_display_name_ = 'Python Service'
    _svc_description_ = 'Python Service Description'

    @classmethod
    def parse_command_line(cls):
        '''
        ClassMethod to parse the command line
        '''
        win32serviceutil.HandleCommandLine(cls)

    def __init__(self, args):
        '''
        Constructor of the winservice
        '''
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        '''
        Called when the service is asked to stop
        '''
        self.stop()
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        '''
        Called when the service is asked to start
        '''
        self.start()
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        self.main()

    def start(self):
        '''
        Override to add logic before the start
        eg. running condition
        '''
        pass

    def stop(self):
        '''
        Override to add logic before the stop
        eg. invalidating running condition
        '''
        pass

    def main(self):
        '''
        Main class to be ovverridden to add logic
        '''
        pass

class PowerMasterUPS(SMWinservice):
    _svc_name_ = "PowerMasterUPS"
    _svc_display_name_ = "PowerMasterUPS"
    _svc_description_ = "PowerMasterUPS will Shutdown Windows when UPS battery is depleting"

    def start(self):
        self.isrunning = True

    def stop(self):
        self.isrunning = False

    def main(self):
        while self.isrunning:
            # my app code here

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

解决方法

  • 动态添加脚本路径:替换硬编码的路径添加方式,改为动态获取当前脚本所在目录,避免路径错误:
    # 替换原sys.path.append("C:\\")为以下代码
    sys.path.append(os.path.dirname(os.path.abspath(__file__)))
    
  • 在脚本目录执行命令:安装、调试服务时,先切换到PowerMasterUPS.py所在的目录,再执行命令,示例:
    cd C:\实际脚本所在目录路径
    python PowerMasterUPS.py install
    python PowerMasterUPS.py debug
    
  • 检查服务运行权限:Windows服务默认以Local System账户运行,确认该账户有权限访问脚本所在目录;必要时可修改服务的登录账户为具备访问权限的用户。
  • 添加路径到Python全局环境:在Python的site-packages目录下创建powermasterups.pth文件,文件内容为脚本所在的绝对路径,让Python全局环境能识别该模块。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:47:06