• 写一个Python的windows服务


    1. 安装pywin32和pyinstaller

    pip install pywin32
    pip install pyinstaller
    

    2.写一个服务Demo

    # -*- coding: utf-8 -*-
    import sys
    
    import win32event
    import win32service
    import win32serviceutil
    import servicemanager
    import subprocess
    import logging
    import inspect
    import os
    
    
    class ScreenRecorderService(win32serviceutil.ServiceFramework):
        _svc_name_ = "ScreenRecorderService"
        _svc_display_name_ = "Screen Recorder Service"
        _svc_description_ = "Screen Recorder Service"
        _svc_data_dir = 'D:\ScreenRecorder'
        _ffmpeg_proc = None
    
        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('[ScreenRecorderService]')
    
            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('Screen Recorder Service is Starting ...')
                self.start()
                self.logger.info('Screen Recorder Service Started')
                import time
                time.sleep(3)
                self.logger.info('Screen Recorder Service ffmpeg run')
                ffmpeg = r'C:WindowsSystem32ffmpeg.exe'
                cmd = r'%s -f gdigrab -framerate 10 -i desktop D:\output.mkv -y' % ffmpeg
                self.logger.info(cmd)
                self._ffmpeg_proc = subprocess.Popen(cmd, shell=True)
                try:
                    sys.exit(self._ffmpeg_proc.wait())
                except SystemExit as e:
                    self.logger.warn('Exception : %s' % e)
                self.logger.info('Screen Recorder Service ffmpeg stop')
                win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
                self._ffmpeg_proc.kill()
                self.logger.info('Screen Recorder Service 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('Screen Recorder Service is Stopping ...')
            self.stop()
            self.logger.info('Screen Recorder 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)
            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(ScreenRecorderService)
            servicemanager.StartServiceCtrlDispatcher()
        else:
            win32serviceutil.HandleCommandLine(ScreenRecorderService)
    
    

    3.冻结二进制

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

    4.运行服务

    distMyService.exe install
    sc start MyService
    
  • 相关阅读:
    学习笔记TF034:实现Word2Vec
    学习笔记TF033:实现ResNet
    学习笔记TF032:实现Google Inception Net
    学习笔记TF031:实现VGGNet
    学习笔记TF030:实现AlexNet
    学习笔记TF029:实现进阶卷积网络
    学习笔记TF028:实现简单卷积网络
    学习笔记TF027:卷积神经网络
    学习笔记TF026:多层感知机
    学习笔记TF025:自编码器
  • 原文地址:https://www.cnblogs.com/fangying7/p/9563484.html
Copyright © 2020-2023  润新知