python程序封装为win32服务的方法
本文实例为大家分享了python程序封装为win32服务的具体代码,供大家参考,具体内容如下
#encoding=utf-8 importos importsys importwinerror importwin32serviceutil importwin32service importwin32event importservicemanager classPythonService(win32serviceutil.ServiceFramework): #服务名 _svc_name_="PythonService1" #服务显示名称 _svc_display_name_="PythonServiceDemo" #服务描述 _svc_description_="Pythonservicedemo." def__init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop=win32event.CreateEvent(None,0,0,None) self.logger=self._getLogger() self.isAlive=True def_getLogger(self): importlogging importos importinspect logger=logging.getLogger('[PythonService]') this_file=inspect.getfile(inspect.currentframe()) dirpath=os.path.abspath(os.path.dirname(this_file)) handler=logging.FileHandler(os.path.join(dirpath,"service.log")) formatter=logging.Formatter('%(asctime)s%(name)-12s%(levelname)-8s%(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.INFO) returnlogger defSvcDoRun(self): importtime self.logger.error("svcdorun....") try: whileself.isAlive: self.logger.error("Iamalive.") time.sleep(1) #等待服务被停止 #win32event.WaitForSingleObject(self.hWaitStop,win32event.INFINITE) exceptExceptionase: self.logger.error(e) time.sleep(60) defSvcStop(self): #先告诉SCM停止这个过程 self.logger.error("svcdostop....") self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) #设置事件 win32event.SetEvent(self.hWaitStop) self.isAlive=False if__name__=='__main__': iflen(sys.argv)==1: try: src_dll=os.path.abspath(servicemanager.__file__) servicemanager.PrepareToHostSingle(PythonService) servicemanager.Initialize("PythonService",src_dll) servicemanager.StartServiceCtrlDispatcher() exceptExceptionase: print(e) #ifdetails[0]==winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: #win32serviceutil.usage() else: win32serviceutil.HandleCommandLine(PythonService)#参数和上述定义类名一致 #pipinstallpywin32 #安装服务 #pythonPythonService.pyinstall #让服务自动启动 #pythonPythonService.py--startupautoinstall #启动服务 #pythonPythonService.pystart #重启服务 #pythonPythonService.pyrestart #停止服务 #pythonPythonService.pystop #删除/卸载服务 #pythonPythonService.pyremove #在用户变量处去掉python路径,然后在环境变量加入python路径 #C:\Users\zhongjianhui\AppData\Local\Programs\Python\Python36\Lib\site-packages\pywin32_system32; #C:\Users\zhongjianhui\AppData\Local\Programs\Python\Python36\Lib\site-packages\win32; #C:\Users\zhongjianhui\AppData\Local\Programs\Python\Python36\Scripts\; #C:\Users\zhongjianhui\AppData\Local\Programs\Python\Python36\
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。