Python写自动化之写一个Windows 服务

Python 写windows 服务,需要使用 pywin32包。

直接上代码:

#encoding=utf8'''Created on 2014-7-1@author: wangmengnan'''import osimport sysimport win32serviceutilimport win32serviceimport win32eventclass PythonService(win32serviceutil.ServiceFramework):#服务名_svc_name_ = "PythonService"#服务显示名称_svc_display_name_ = "Python Service Demo"#服务描述_svc_description_ = "Python service demo."def __init__(self,args):win32serviceutil.ServiceFramework.__init__(self,args)self.hWaitStop = win32event.CreateEvent(None,0,0,None)self.logger = self._getLogger()self.isAlive = Truedef _getLogger(self):import loggingimport osimport inspectlogger = logging.getLogger('[PythonService]')this_file = inspect.getfile(inspect.currentframe())dirpath = os.path.abspath(os.path.dirname(this_file))handler = loggint.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)return loggerdef SvcDoRun(self):import timeself.logger.error("svc do run…")while self.isAlive:self.logger.error("I am alive.")time.sleep(1)def SvcStop(self):self.logger.error("svc do stop…")self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)#设置事件win32event.SetEvent(self.hWaitStop)self.isAlive = Falseif __name__ == '__main__':win32serviceutil.HandleCommandLine(PythonService)

程序写好后,需要对服务进行安装、以及启动等操作,命令如下:

安装服务:

python service.py install让服务自动启动:

python service.py –startup auto install启动服务:

python service.py start

重启服务:python service.py restart

停止服务:python service.py stop

删除/卸载服务python service.py remove安装并启动服务后,可以通过 计算机 -> 管理 ->服务和应用程序 ->服务 里面找到我们自己写的服务,图片如下:

,为你的难过而快乐的是敌人,

Python写自动化之写一个Windows 服务

相关文章:

你感兴趣的文章:

标签云: