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:\Windows\System32\ffmpeg.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.运行服务

dist\MyService.exe install
sc start MyService

写一个Python的windows服务的更多相关文章

  1. 写一个python的服务监控程序

    写一个python的服务监控程序 前言: Redhat下安装Python2.7 rhel6.4自带的是2.6, 发现有的机器是python2.4. 到python网站下载源代码,解压到Redhat上, ...

  2. Python做windows服务

    Python做windows服务(多进程服务),并结束多进程 Python中_,__,__xx__的区别 在注册MyWinService服务时,再使用 "sc delete 服务器名称&qu ...

  3. 如何创建一个标准的Windows服务

    出处:http://www.cnblogs.com/wuhuacong/archive/2009/02/11/1381428.html 如何创建一个标准的Windows服务 在很多时候,我们需要一个定 ...

  4. 如何手动写一个Python脚本自动爬取Bilibili小视频

    如何手动写一个Python脚本自动爬取Bilibili小视频 国庆结束之余,某个不务正业的码农不好好干活,在B站瞎逛着,毕竟国庆嘛,还让不让人休息了诶-- 我身边的很多小伙伴们在朋友圈里面晒着出去游玩 ...

  5. laravel学习:php写一个简单的ioc服务管理容器

    php写一个简单的ioc服务管理容器 原创: 陈晨 CoderStory 2018-01-14 最近学习laravel框架,了解到laravel核心是一个大容器,这个容器负责几乎所有服务组件的实例化以 ...

  6. Python-windows服务-重启自动化

    一. 前言 有了上一篇的“python初学”的基础,咱们就有了python的开发包,有了开发环境IDE,那我们就可以干活了.我的第一个选题就是让我们的windows服务可以按照我们的意愿进行自动重启. ...

  7. python管理Windows服务

    上一篇介绍了pywin32模块,它的win32service子模块提供了对服务管理API的包装,相关API如下: ChangeServiceConfig ChangeServiceConfig2 Cl ...

  8. 如何成功发布一个MSMQ的Windows服务

    因为MSMQ的使用需要不断的查看队列是否有新消息,所以一般是结合Windows的服务,当然也可以用一个不关闭的Winform程序,不过前者更好一些,不怕被人误关. 完成MSMQ的WindowsServ ...

  9. 写一个python脚本监控在linux中的进程

    在虚拟机中安装Linux中的CentOS7系统 https://baijiahao.baidu.com/s?id=1597320700700593557&wfr=spider&for= ...

随机推荐

  1. Dropping water balloons (入门dp)

    2017-08-12 18:36:24 writer:pprp 最近刚刚接触动态规划,感觉状态的查找和转移自己很难想到,都是面向题解编程,但是一开始都是这样了,只有相信我可以独立自己解决动态规划这类问 ...

  2. 测试php语句执行时间

    $start = microtime(true); $elapsed = microtime(true) - $start; echo "That took $elapsed seconds ...

  3. Memcache课程

    这套Memcache课程今天正式上线,http://www.yzmedu.com/course/53,总计6集,包括Memcache缓存技术和Memcache用户跨域技术,后面即将发布网上最全的微信小 ...

  4. MATLAB 2014a (8.3) Compiler Runtime (MCR)

    在安装的时候可以 ./install -H 界面化安装到自己目录下 MATLAB 2014a (8.3) Runtime Compiler (MCR) Errors when trying to la ...

  5. jquery插件之jquery-ui

    1.jQuery UI是在jQuery的基础上,利用jQuery的扩展性,设计的插件.提供了一些常用的界面元素,如:模态框.日期控件等. 2.下载地址:http://jqueryui.com/down ...

  6. thinkphp3.2.3 + nginx 配置二级域名

    使用的是阿里云centOS.74 第一步: 配置urlpath server { listen ; server_name www.xxxx.com xxxx.com; root /data/www/ ...

  7. UVA-1623 Enter The Dragon (贪心)

    题目大意:有n个装满水的湖,m天.每天可能下雨也可能晴天,只要下雨就会把湖填满,若已满,则发洪水.有一台只能在晴天使用的抽水机,每次抽水只能抽一个湖,并且全部抽光.问是否存在一种使得不发洪水的抽水方案 ...

  8. ZOJ 2599 Graduated Lexicographical Ordering ★(数位DP)

    题意 定义两个数的比较方法,各位数字之和大的数大,如果数字和相等则按字典序比较两个数的大小.输入n,k,求:1.数字k的排名:2.排名为k的数. 思路 算是一类经典的统计问题的拓展吧~ 先来看第一问. ...

  9. edm 邮件制作指南

    格式编码 1.页面宽度请设定在 600px 到 800px 以内,长度 1024px 以内. 2.html 编码请使用 utf-8. 3.html 代码在 15KB 以内.(各个邮箱的收件标准不一样, ...

  10. Ansible 小手册系列 十二(Facts)

    Facts 是用来采集目标系统信息的,具体是用setup模块来采集得. 使用setup模块来获取目标系统信息 ansible hostname -m setup 仅显示与ansible相关的内存信息 ...