python實現編寫windows服務

使用python編寫windows服務python

  最近測試服務器上常常發生磁盤空間不足,每次手動清除比較麻煩,因此寫個windows服務定時清理下。中間也遇到過幾個坑,一塊兒記錄下來。git

  1.python實現windows服務須要藉助第三方庫pywin32。可以使用  pip3 命令下載。windows

  代碼以下:服務器

# 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,輸入以下命令:app

#安裝服務
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」,意思是「服務沒有及時響應啓動或控制請求」。this

 

 2.解決方案:將Python36\Lib\site-packages\win32路徑下的pythonservice.exe註冊一下。spa

                   註冊命令:pythonservice.exe /register日誌

 

3.這很尷尬。。。缺乏pywintypes36.dll。找下,在Python36\Lib\site-packages\pywin32_system32路徑。code

  解決方法:設置到環境變量或者將此dll copy到Python36\Lib\site-packages\win32。

  註冊完後執行python Clearjob.py start

服務運行成功!

相關文章
相關標籤/搜索