• Python 实现windows后台服务


    # -*- coding: utf-8 -*-
    import sys
    
    import win32api
    import win32con
    import win32event
    import win32service
    import win32serviceutil
    import servicemanager
    import logging
    import os
    from http.server import HTTPServer, CGIHTTPRequestHandler
    
    
    class HTTPFilerServer(win32serviceutil.ServiceFramework):
        _svc_name_ = "HTTPFileServer"
        _svc_display_name_ = "HTTP File Server"
        _svc_description_ = "HTTP File Server"
        _svc_data_dir = 'D:\ScreenRecorder'
    
        def __init__(self, args):
            win32serviceutil.ServiceFramework.__init__(self, args)
            self.stop_event = win32event.CreateEvent(None, 0, 0, None)
            self.logger = self._getLogger()
    
        def _getLogger(self):
    
            logger = logging.getLogger('[HTTPFileServer]')
            dirpath = os.path.abspath(self._svc_data_dir)
            handler = logging.FileHandler(os.path.join(dirpath, self._svc_name_ + ".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):
            self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
            try:
                self.ReportServiceStatus(win32service.SERVICE_RUNNING)
                self.logger.info('HTTP File Server is Starting ...')
                self.start()
                self.logger.info('HTTP File Server Started')
                import time
                time.sleep(3)
                os.chdir(self._svc_data_dir)
                httpd = HTTPServer(('', 8080), CGIHTTPRequestHandler)
                httpd.serve_forever()
    
                win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
                self.logger.info('HTTP File Server Shutdown')
            except BaseException as e:
                self.logger.warn('Exception : %s' % e)
                self.SvcStop()
    
        def SvcStop(self):
            self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
            self.logger.info('HTTP File Server is Stopping ...')
            self.stop()
            self.logger.info('HTTP File Server Service Stopped')
            win32event.SetEvent(self.stop_event)
            self.ReportServiceStatus(win32service.SERVICE_STOPPED)
    
        def start(self):
            if not os.path.exists(self._svc_data_dir):
                os.mkdir(self._svc_data_dir)
                win32api.SetFileAttributes(self._svc_data_dir, win32con.FILE_ATTRIBUTE_HIDDEN)
            else:
                pass
    
        def stop(self):
            pass
    
        def log(self, msg):
            servicemanager.LogInfoMsg(str(msg))
    
    
    if __name__ == "__main__":
        if len(sys.argv) == 1:
            servicemanager.Initialize()
            servicemanager.PrepareToHostSingle(HTTPFilerServer)
            servicemanager.StartServiceCtrlDispatcher()
        else:
            win32serviceutil.HandleCommandLine(HTTPFilerServer)
    
  • 相关阅读:
    CSS 与 HTML5 响应式图片
    Sublime Text3中最常用的快捷键
    JSON.parse这个是啥?
    页面的拼装配置Appache SSI
    如何保障mysql和redis之间的数据一致性?(转发)
    ORACLE异常ORA-01843 || ORA-14411 || Invalid column index
    Cause: java.sql.SQLException: 无效的列索引
    java.lang.IllegalArgumentException: host parameter is null
    java.lang.ClassNotFoundException: org.apache.commons.codec.DecoderException 异常
    java.sql.SQLIntegrityConstraintViolationException: ORA-00001: 违反唯一约束条件
  • 原文地址:https://www.cnblogs.com/fangying7/p/9569120.html
Copyright © 2020-2023  润新知