写一个Python的windows服务

2021-07-10 00:06

阅读:794

标签:imp   etl   cti   comm   exce   进制   sage   port   repo   

1. 安装pywin32和pyinstaller

pip install pywin32
pip install pyinstaller

2.写一个服务Demo

# -*- coding: utf-8 -*-
import sys
import time

import win32api
import win32event
import win32service
import win32serviceutil
import servicemanager
import logging
import inspect
import os


class MyService(win32serviceutil.ServiceFramework):
    _svc_name_ = "MyService"
    _svc_display_name_ = "My Service"
    _svc_description_ = "My Service"

    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('[MyService]')

        this_file = inspect.getfile(inspect.currentframe())
        dirpath = os.path.abspath(os.path.dirname(this_file))
        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('start ...')
            self.start()
            self.logger.info('wait ...')
            win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
            self.logger.info('done!')
        except BaseException as e:
            self.logger.warn('Exception : %s' % e)
            self.SvcStop()

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.logger.info('stopping ...')
        self.stop()
        self.logger.info('stopped.')
        win32event.SetEvent(self.stop_event)
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)

    def start(self):
        time.sleep(10000)

    def stop(self):
        pass

    def log(self, msg):
        servicemanager.LogInfoMsg(str(msg))

    def sleep(self, minute):
        win32api.Sleep((minute * 1000), True)


if __name__ == "__main__":
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(MyService)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(MyService)

3.冻结二进制

pyinstaller -F MyService.py --hidden-import=win32timezone

4.运行服务

dist\MyService.exe install
sc start MyService

写一个Python的windows服务

标签:imp   etl   cti   comm   exce   进制   sage   port   repo   

原文地址:https://www.cnblogs.com/fangying7/p/9563484.html


评论


亲,登录后才可以留言!