欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python程序封装为win32服务的方法

程序员文章站 2022-07-17 17:46:35
本文实例为大家分享了python程序封装为win32服务的具体代码,供大家参考,具体内容如下 # encoding=utf-8 import os impor...

本文实例为大家分享了python程序封装为win32服务的具体代码,供大家参考,具体内容如下

# encoding=utf-8
import os
import sys
import winerror
import win32serviceutil
import win32service
import win32event
import servicemanager
 
 
class pythonservice(win32serviceutil.serviceframework):
 
 # 服务名
 _svc_name_ = "pythonservice1"
 # 服务显示名称
 _svc_display_name_ = "pythonservicedemo"
 # 服务描述
 _svc_description_ = "python service demo."
 
 def __init__(self, args):
  win32serviceutil.serviceframework.__init__(self, args)
  self.hwaitstop = win32event.createevent(none, 0, 0, none)
  self.logger = self._getlogger()
  self.isalive = true
 
 def _getlogger(self):
  import logging
  import os
  import inspect
 
  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.error("svc do run....")
  try:
   while self.isalive:
    self.logger.error("i am alive.")
    time.sleep(1)
    # 等待服务被停止
    # win32event.waitforsingleobject(self.hwaitstop, win32event.infinite)
  except exception as e:
   self.logger.error(e)
   time.sleep(60)
 
 def svcstop(self):
  # 先告诉scm停止这个过程
  self.logger.error("svc do stop....")
  self.reportservicestatus(win32service.service_stop_pending)
  # 设置事件
  win32event.setevent(self.hwaitstop)
  self.isalive = false
 
 
if __name__ == '__main__':
 if len(sys.argv) == 1:
  try:
   src_dll = os.path.abspath(servicemanager.__file__)
   servicemanager.preparetohostsingle(pythonservice)
   servicemanager.initialize("pythonservice", src_dll)
   servicemanager.startservicectrldispatcher()
  except exception as e:
   print(e)
   #if details[0] == winerror.error_failed_service_controller_connect:
    #win32serviceutil.usage()
 else:
  win32serviceutil.handlecommandline(pythonservice) # 参数和上述定义类名一致
 
#pip install pywin32
 
# 安装服务
# 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
 
 
# 在用户变量处去掉python路径,然后在环境变量加入python路径
# c:\users\zhongjianhui\appdata\local\programs\python\python36\lib\site-packages\pywin32_system32;
# c:\users\zhongjianhui\appdata\local\programs\python\python36\lib\site-packages\win32;
# c:\users\zhongjianhui\appdata\local\programs\python\python36\scripts\;
#c:\users\zhongjianhui\appdata\local\programs\python\python36\

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。