分享

Python 编写Windows服务程序:将Python作为Windows服务启动

 看风景D人 2014-01-07

Python程序作为Windows服务启动,需要安装pywin32包。下载路径:

http:///projects/pywin32/files/pywin32/


 


#-*- coding:utf-8 -*-

  1. import win32serviceutil   
  2. import win32service   
  3. import win32event   
  4.   
  5. class PythonService(win32serviceutil.ServiceFramework):   
  6.     """ 
  7.     Usage: 'PythonService.py [options] install|update|remove|start [...]|stop|restart [...]|debug [...]' 
  8.     Options for 'install' and 'update' commands only: 
  9.      --username domain\username : The Username the service is to run under 
  10.      --password password : The password for the username 
  11.      --startup [manual|auto|disabled|delayed] : How the service starts, default = manual 
  12.      --interactive : Allow the service to interact with the desktop. 
  13.      --perfmonini file: .ini file to use for registering performance monitor data 
  14.      --perfmondll file: .dll file to use when querying the service for 
  15.        performance data, default = perfmondata.dll 
  16.     Options for 'start' and 'stop' commands only: 
  17.      --wait seconds: Wait for the service to actually start or stop. 
  18.                      If you specify --wait with the 'stop' option, the service 
  19.                      and all dependent services will be stopped, each waiting 
  20.                      the specified period. 
  21.     """  
  22.     #服务名   
  23.     _svc_name_ = "PythonService"  
  24.     #服务显示名称   
  25.     _svc_display_name_ = "Python Service Demo"  
  26.     #服务描述   
  27.     _svc_description_ = "Python service demo."  
  28.   
  29.     def __init__(self, args):   
  30.         win32serviceutil.ServiceFramework.__init__(self, args)   
  31.         self.hWaitStop = win32event.CreateEvent(None00None)  
  32.         self.logger = self._getLogger()  
  33.         self.isAlive = True  
  34.           
  35.     def _getLogger(self):  
  36.         import logging  
  37.         import os  
  38.         import inspect  
  39.           
  40.         logger = logging.getLogger('[PythonService]')  
  41.           
  42.         this_file = inspect.getfile(inspect.currentframe())  
  43.         dirpath = os.path.abspath(os.path.dirname(this_file))  
  44.         handler = logging.FileHandler(os.path.join(dirpath, "service.log"))  
  45.           
  46.         formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')  
  47.         handler.setFormatter(formatter)  
  48.           
  49.         logger.addHandler(handler)  
  50.         logger.setLevel(logging.INFO)  
  51.           
  52.         return logger  
  53.   
  54.     def SvcDoRun(self):  
  55.         import time  
  56.         self.logger.error("svc do run....")   
  57.         while self.isAlive:  
  58.             self.logger.error("I am alive.")  
  59.             time.sleep(1)  
  60.         # 等待服务被停止    
  61.         #win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)    
  62.               
  63.     def SvcStop(self):   
  64.         # 先告诉SCM停止这个过程    
  65.         self.logger.error("svc do stop....")  
  66.         self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)   
  67.         # 设置事件    
  68.         win32event.SetEvent(self.hWaitStop)   
  69.         self.isAlive = False  
  70.   
  71. if __name__=='__main__':   
  72.     win32serviceutil.HandleCommandLine(PythonService)  


安装服务

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


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多