Python 實現windows後台服務

來源:互聯網
上載者:User

標籤:comm   window   dispatch   shutdown   wait   message   lin   code   handler   

# -*- coding: utf-8 -*-import sysimport win32apiimport win32conimport win32eventimport win32serviceimport win32serviceutilimport servicemanagerimport loggingimport osfrom http.server import HTTPServer, CGIHTTPRequestHandlerclass 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)

Python 實現windows後台服務

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.