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

将Python脚本作为Windows Service运行时出现servicemanager模块找不到错误

问题:Windows服务启动时提示找不到servicemanager模块

我有一个Django学习项目,用waitress做WSGI服务器托管网站,命令行运行脚本完全正常。但配置成Windows服务时,启动服务就提示ModuleNotFoundError,找不到servicemanager模块。已经在虚拟环境和全局Python里都装了pywin32和servicemanager,甚至重启过机器,还是不行。

服务启动错误

使用的Python脚本

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
from waitress import serve
from django_project.wsgi import application

class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "PagesService"
    _svc_display_name_ = "Pages Service"

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

    def SvcStop(self):
        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):
        serve(application, port='8000')

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

pip freeze生成的requirements.txt

argcomplete==1.12.3
asgiref==3.6.0
atomicwrites==1.4.1
attrs==23.1.0
bottle==0.12.18
certifi==2022.12.7
chardet==3.0.4
colorama==0.4.6
Django==4.1.8
idna==2.10
more-itertools==9.1.0
mssql-django==1.2
packaging==23.1
pluggy==0.13.1
prettytable==0.7.2
py==1.11.0
PyHamcrest==2.0.2
pymongo==3.11.0
pyodbc==4.0.39
pytest==5.4.3
pytz==2023.3
pywin32==306
requests==2.24.0
servicemanager==2.0.10
sqlparse==0.4.4
tzdata==2023.3
urllib3==1.25.11
waitress==2.1.2
wcwidth==0.2.6

解决办法

  • 指定虚拟环境Python安装服务:Windows服务默认可能调用全局Python,而非你的项目虚拟环境。安装服务时必须明确使用虚拟环境的Python路径,比如:
    C:\your\venv\Scripts\python.exe your_script.py install
    
  • 卸载第三方servicemanager包:pywin32本身已经内置了servicemanager模块,你安装的第三方servicemanager==2.0.10会导致模块冲突,执行以下命令卸载:
    pip uninstall servicemanager
    
  • 重新注册pywin32服务组件:进入虚拟环境的Scripts目录,执行以下命令确保pywin32的服务相关组件正确注册:
    python pywin32_postinstall.py -install
    
  • 排查Python路径问题:可以在脚本开头添加调试代码,输出服务运行时的Python模块路径,方便定位问题:
    import sys
    with open('service_path_log.txt', 'w') as f:
        f.write('\n'.join(sys.path))
    
  • 重新部署服务:先卸载现有服务,再用虚拟环境Python重新安装并启动:
    C:\your\venv\Scripts\python.exe your_script.py remove
    C:\your\venv\Scripts\python.exe your_script.py install
    net start PagesService
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 18:57:55