最近做了公司签到的小工具,有同事要求做成Windows服务,开机自启。先说下怎么用Python写Windows服务程序。

 #encoding=utf-8
import win32serviceutil
import win32service
import win32event
import win32timezone
import os class PythonService(win32serviceutil.ServiceFramework):
_svc_name_ = 'PythonService' #服务名称
_svc_display_name_ = 'regMeal'
_svc_description_ = '每天晚上6:40后自动签到' def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
self.logger = self._getLogger()
self.run = True def _getLogger(self):
import inspect
import logging
logger = logging.getLogger('[PythonService]')
this_file = inspect.getfile(inspect.currentframe())
dirpath = os.path.abspath(os.path.dirname(this_file))
handler = logging.FileHandler(os.path.join(dirpath,'service.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):
import time
import readconfig
import regMeal
self.logger.info('service is run...')
while self.run:
self.logger.info('service is running...')
paraList = readconfig.readConfig()
bFlag = regMeal.main(paraList[0],paraList[1],paraList[2])
time.sleep(2) def SvcStop(self):
self.logger.info('service is stop.')
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
self.run = False if __name__ == '__main__':
import sys
import servicemanager
if len(sys.argv) == 1:
try:
evtsrc_dll = os.path.abspath(servicemanager.__file__)
servicemanager.PrepareToHostSingle(PythonService)
servicemanager.Initialize('PythonService',evtsrc_dll)
servicemanager.StartServiceCtrlDispatcher()
except win32service.error as details:
import winerror
if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
win32serviceutil.usage()
else:
win32serviceutil.HandleCommandLine(PythonService)

推荐大家对比网上其他的人的代码对照看下。SvcDoRun这个函数里面放的就是你实际想做的事情。

安装服务

python PythonService.py install

让服务自动启动

python PythonService.py --startup auto install 

启动服务

python PythonService.py start

重启服务

python PythonService.py restart

停止服务

python PythonService.py stop

删除/卸载服务

python PythonService.py remove

我自己是用pyinstaller打包成exe给别人用的。

PS:脚本编好之后,调试了很久。刚开始会报服务无法启动的问题。具体的排查方式可以看Windows事件查看。

最新文章

  1. PHPstorm同步文件时与ftp断开连接
  2. 最详细的hadoop2.2.0集群的HA高可靠的最简单配置
  3. hdu 1279 验证角谷猜想
  4. ural 1338. Automobiles
  5. MyEclipse使用总结——MyEclipse文件查找技巧 ctrl+shift+R ctrl+H
  6. javascript 作用域
  7. android135 360 来电去电归属地显示,自定义toast,
  8. C#基础学习第一天(.net菜鸟的成长之路-零基础到精通)
  9. MyBatis动态SQL与模糊查询
  10. EF Core Model更新迁移
  11. BZOJ1058或洛谷1110 [ZJOI2007]报表统计
  12. python自学第10天,生成器
  13. PowerShell使用ServicePrincipal登陆Azure
  14. struts2:OGNL表达式,遍历List、Map集合;投影的使用
  15. linux命令瞎记录find xargs
  16. Caused by: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'zoneId' in 'class java.lang.String'
  17. ASP.net 完整登录流程
  18. Regex.Split
  19. Unity性能优化之Draw Call(转)
  20. 项目使用Nuget,然后SVN checkout后显示缺少引用

热门文章

  1. 公钥基本结构(PKI)的概念
  2. TLE - Time Limit Exceeded
  3. noip模拟赛 hungary
  4. CODEVS1281 Xn数列 (矩阵乘法+快速乘)
  5. 洛谷——P2676 超级书架
  6. Workflow:实现一个简单的审批流程
  7. HDU 5266 bc# 43 LCA+跳表
  8. 《Java程序猿面试笔试宝典》之字符串创建与存储的机制是什么
  9. 苹果iPhone6为何拯救不了富士康?
  10. 一个基于cocos2d-x 3.0和Box2d的demo小程序