加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python创建Windows 服务

发布时间:2020-12-17 17:18:43 所属栏目:Python 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 #encoding=utf8'''Created on 2014-7-1@author: wangmengnan'''import osimport sysimport win32serviceutilimport win32serviceimport win32eventcla

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

#encoding=utf8

'''
Created on 2014-7-1

@author: wangmengnan
'''


import os
import sys
import win32serviceutil
import win32service
import win32event

class 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,None)
        self.logger = self._getLogger()
        self.isAlive = True
    
    def _getLogger(self):
        import logging
        import os
        import inspect
        
        logger = 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 logger
    def SvcDoRun(self):
        import time
        self.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 = False


if __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

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

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读