zoukankan      html  css  js  c++  java
  • python实现编写windows服务

    使用python编写windows服务

      最近测试服务器上经常发生磁盘空间不足,每次手动清除比较麻烦,所以写个windows服务定时清理下。中间也遇到过几个坑,一起记录下来。

      1.python实现windows服务需要借助第三方库pywin32。可使用  pip3 命令下载。

      代码如下:

    # ZPF
    # encoding=utf-8
    import win32timezone
    from logging.handlers import TimedRotatingFileHandler
    import win32serviceutil
    import win32service
    import win32event
    import os
    import logging
    import inspect
    import time
    import shutil
    
    
    class PythonService(win32serviceutil.ServiceFramework):
        _svc_name_ = "PythonService"                    #服务名
        _svc_display_name_ = "Clearjob"                 #job在windows services上显示的名字
        _svc_description_ = "Clear system files"        #job的描述
    
        def __init__(self, args):
            win32serviceutil.ServiceFramework.__init__(self, args)
            self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
            self.logger = self._getLogger()
            self.path = 'D:\WebSite'
            self.T = time.time()
            self.run = True
    
        def _getLogger(self):
            '''日志记录'''
            logger = logging.getLogger('[PythonService]')
            this_file = inspect.getfile(inspect.currentframe())
            dirpath = os.path.abspath(os.path.dirname(this_file))
            if os.path.isdir('%s\log'%dirpath):  #创建log文件夹
                pass
            else:
                os.mkdir('%s\log'%dirpath)
            dir = '%s\log' % dirpath
    
            handler = TimedRotatingFileHandler(os.path.join(dir, "Clearjob.log"),when="midnight",interval=1,backupCount=20)
            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):
            self.logger.info("service is run....")
            try:
                while self.run:
                    self.logger.info('---Begin---')
                    for path, name, file in os.walk('D:\Website'):
                        if path == 'D:\Website':
                            for IISname in name:
                                floder = []
                                for i in os.listdir(os.path.join(path, IISname)):
                                    if i.isdigit():
                                        floder.append(int(i))
                                if len(floder) == 0:
                                    pass
                                elif len(floder) >= 2:  # 设置保留备份
                                    floder.sort()
                                    for x in floder[:(len(floder) - 2)]: 
                                        self.logger.info("delete dir: %s" % os.path.join(os.path.join(path, IISname), str(x)))
                                        shutil.rmtree(os.path.join(os.path.join(path, IISname), str(x)))
    
                    self.logger.info('---End---')
                    time.sleep(10)
    
            except Exception as e:
                self.logger.info(e)
                time.sleep(60)
    
        def SvcStop(self):
            self.logger.info("service is stop....")
            self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
            win32event.SetEvent(self.hWaitStop)
            self.run = False
    
    
    if __name__ == '__main__':
        win32serviceutil.HandleCommandLine(PythonService)

    2.服务启动程序会调用SvcDoRun()。手动停止服务的时候,系统率先调用SvcStop(),将self.run置成False,SvcDoRun()跳出循环,服务停止。

    3.然后将服务安装到windows
    管理员运行cmd,输入如下命令:

    #安装服务
    python Clearjob.py install
    
    #开启服务
    python Clearjob.py start
    
    #停止服务
    python Clearjob.py stop
    
    #移除服务
    python Clearjob.py remove

    异常解决方法

      1.开启服务的时候会出现报错“The service did not respond to the start or control request in a timely fashion”,意思是“服务没有及时响应启动或控制请求”。

     2.解决方案:将Python36Libsite-packageswin32路径下的pythonservice.exe注册一下。

                       注册命令:pythonservice.exe /register

    3.这很尴尬。。。缺少pywintypes36.dll。找下,在Python36Libsite-packagespywin32_system32路径。

      解决方法:设置到环境变量或者将此dll copy到Python36Libsite-packageswin32。

      注册完后执行python Clearjob.py start

    服务运行成功!

     

     

  • 相关阅读:
    表空间及组成表空间的物理文件
    MVCC
    innodb结构解析工具---innodb_ruby
    慢查询日志 与 general_log
    思考mysql内核之初级系列
    mysql内核源代码深度解析 缓冲池 buffer pool 整体概述
    change buffer
    python 学习笔记 copy
    xargs
    给tcpdump加点颜色看看
  • 原文地址:https://www.cnblogs.com/shenh/p/8931620.html
Copyright © 2011-2022 走看看