service_adapter.py
作者:互联网
# -*- coding:utf-8 -*- import os import sys import time import servicemanager import win32serviceutil import win32service import win32event import winerror class ServiceAdapter(win32serviceutil.ServiceFramework): _svc_name_ = "ServiceAdapter" _svc_display_name_ = 'Service_Adapter' _svc_description_ = 'Windows service adapter' def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.stop_event = win32event.CreateEvent(None, 0, 0, None) def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_START_PENDING) self.start() self.ReportServiceStatus(win32service.SERVICE_RUNNING) self.running() # Write a stop message. servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, '') ) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.stop() self.log("SetEvent stop_event") win32event.SetEvent(self.stop_event) self.log("ReportServiceStatus SERVICE_STOPPED") self.ReportServiceStatus(win32service.SERVICE_STOPPED) self.log("ReportServiceStatus SERVICE_STOPPED end.") @classmethod def service_main(cls): if len(sys.argv) == 1: try: event_src_dll = os.path.abspath(servicemanager.__file__) servicemanager.PrepareToHostSingle(cls) servicemanager.Initialize(cls.__name__, event_src_dll) servicemanager.StartServiceCtrlDispatcher() except Exception as exp: if exp.args[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: win32serviceutil.usage() else: try: win32serviceutil.HandleCommandLine(cls) except Exception as ex: cls.log(ex) exit(1) def start(self): self.log("start") pass def stop(self): self.log("stop") pass def running(self): while True: self.log("running") # self._log() time.sleep(5) @classmethod def log(cls, msg): with open("{}.log".format(cls._svc_name_), "a") as fp: fp.write("{} {}".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), msg)) fp.write("\n") if __name__ == '__main__': # program_path = os.path.abspath(os.path.dirname(__file__)) # ServiceAdapter.log(program_path) try: ServiceAdapter.service_main() except (SystemExit, KeyboardInterrupt): raise except: print("Something went bad!") import traceback traceback.print_exc() pass
标签:__,log,service,adapter,py,SERVICE,servicemanager,import,self 来源: https://www.cnblogs.com/munan-zhou/p/12407582.html