1. 程式人生 > >Python 實現windows後臺服務

Python 實現windows後臺服務

report comm port _for utf-8 nag argv wait bject

# -*- 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)

Python 實現windows後臺服務