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