Python制作Windows系统服务
最近有个Python程序需要安装并作为Windows系统服务来运行,过程中碰到一些坑,整理了一下。
Python服务类
首先Python程序需要调用一些Windows系统API才能作为系统服务,具体内容如下:
#!/usr/bin/envpython #-*-coding:utf-8-*- importsys importtime importwin32api importwin32event importwin32service importwin32serviceutil importservicemanager classMyService(win32serviceutil.ServiceFramework): _svc_name_="MyService" _svc_display_name_="MyService" _svc_description_="MyService" def__init__(self,args): self.log('init') win32serviceutil.ServiceFramework.__init__(self,args) self.stop_event=win32event.CreateEvent(None,0,0,None) defSvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_START_PENDING) try: self.ReportServiceStatus(win32service.SERVICE_RUNNING) self.log('start') self.start() self.log('wait') win32event.WaitForSingleObject(self.stop_event,win32event.INFINITE) self.log('done') exceptBaseExceptionase: self.log('Exception:%s'%e) self.SvcStop() defSvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.log('stopping') self.stop() self.log('stopped') win32event.SetEvent(self.stop_event) self.ReportServiceStatus(win32service.SERVICE_STOPPED) defstart(self): time.sleep(10000) defstop(self): pass deflog(self,msg): servicemanager.LogInfoMsg(str(msg)) defsleep(self,minute): win32api.Sleep((minute*1000),True) if__name__=="__main__": iflen(sys.argv)==1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(MyService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(MyService)
pyinstaller打包
pyinstaller-FMyService.py
测试
#安装服务 dist\MyService.exeinstall #启动服务 scstartMyService #停止服务 scstopMyService #删除服务 scdeleteMyService
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。