Python编写Windows Service服务程序

yipeiwu_com5年前Python基础

 如果你想用Python开发Windows程序,并让其开机启动等,就必须写成windows的服务程序Windows Service,用Python来做这个事情必须要借助第三方模块pywin32,自己去下载然后安装(注意下载符合自己OS的版本)。

1.示例分析

1).幸运的是这里有一个简单的服务模版,足以满足大多数人的要求:

#encoding=utf-8 
#ZPF 
import win32serviceutil 
import win32service 
import win32event 
 
class PythonService(win32serviceutil.ServiceFramework): 
 #服务名 
 _svc_name_ = "PythonService" 
 #服务在windows系统中显示的名称 
 _svc_display_name_ = "Python Service Test" 
 #服务的描述 
 _svc_description_ = "This code is a Python service Test" 
 
 def __init__(self, args): 
  win32serviceutil.ServiceFramework.__init__(self, args) 
  self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) 
 
 def SvcDoRun(self): 
  # 把自己的代码放到这里,就OK 
  # 等待服务被停止 
  win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) 
    
 def SvcStop(self): 
  # 先告诉SCM停止这个过程 
  self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) 
  # 设置事件 
  win32event.SetEvent(self.hWaitStop) 
 
if __name__=='__main__': 
 win32serviceutil.HandleCommandLine(PythonService) 
 #括号里参数可以改成其他名字,但是必须与class类名一致; 

2).解释一下这段代码:在类PythonService的__init__函数执行完后,系统服务开始启动,windows系统会自动调用SvcDoRun函数,这个函数的执行不可以结束,因为结束就代表服务停止。所以当我们放自己的代码在SvcDoRun函数中执行的时候,必须确保该函数不退出,如果退出或者该函数没有正常运行就表示服务停止,windows系统会提示:

3).当停止服务的时候,系统会调用SvcDoStop函数,该函数通过设置标志位等方式让SvcDoRun函数退出,就是正常的停止服务。例子中是通过event事件让SvcDoRun函数停止等待,从而退出该函数,从而使服务停止。

4).注意:系统关机时不会调用SvcDoStop函数,所以这种服务是可以设置为开机自启的。

2.实例

一般都是通过在SvcDoRun函数中设置循环来达到不退出的目的,看例子通过设置标志位run来实现:

#ZPF 
#encoding=utf-8 
import win32serviceutil 
import win32service 
import win32event 
import os 
import logging 
import inspect 
 
class PythonService(win32serviceutil.ServiceFramework): 
 
 _svc_name_ = "PythonService" 
 _svc_display_name_ = "Python Service Test" 
 _svc_description_ = "This is a python service test code " 
 
 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): 
   
  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 
  self.logger.info("service is run....") 
  while self.run: 
   self.logger.info("I am runing....") 
   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__': 
 win32serviceutil.HandleCommandLine(PythonService) 

4.服务操作命令

下面是对上述服务操作的基本命令:

1.安装服务   

python PythonService.py install 

2.让服务自动启动   

python PythonService.py --startup auto install  

3.启动服务  

python PythonService.py start 

4.重启服务

python PythonService.py restart 

5.停止服务   

python PythonService.py stop 

6.删除/卸载服务   

python PythonService.py remove 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python生成密码库功能示例

本文实例讲述了Python生成密码库功能。分享给大家供大家参考,具体如下: 这个代码是将字符的所有组合添加到一个文件中,可以设置密码的最大长度,我这里设置的是8位,但是要有心里准备,生成...

Opencv-Python图像透视变换cv2.warpPerspective的示例

Opencv-Python图像透视变换cv2.warpPerspective的示例

Opencv-Python图像透视变换cv2.warpPerspective 代码如下: # -*- coding:utf-8 -*- import cv2 import numpy...

Python中最好用的命令行参数解析工具(argparse)

Python 做为一个脚本语言,可以很方便地写各种工具。当你在服务端要运行一个工具或服务时,输入参数似乎是一种硬需(当然你也可以通过配置文件来实现)。 如果要以命令行执行,那你需要解析...

学python安装的软件总结

学python安装什么软件? Python开发软件可根据其用途不同分为两种,一种是Python代码编辑器,一种是Python集成开发工具,两者的配合使用可以极大的提高Python开发人员...

python绘制双Y轴折线图以及单Y轴双变量柱状图的实例

python绘制双Y轴折线图以及单Y轴双变量柱状图的实例

近来实验室的师姐要发论文,由于论文交稿时间临近,有一些杂活儿需要处理,作为实验室资历最浅的一批,我这个实习生也就责无旁贷地帮忙当个下手。今天师姐派了一个小活,具体要求是: 给一些训练模型...