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

yipeiwu_com6年前Python基础

本文实例为大家分享了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\

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

相关文章

python通过线程实现定时器timer的方法

本文实例讲述了python通过线程实现定时器timer的方法。分享给大家供大家参考。具体分析如下: 这个python类实现了一个定时器效果,调用非常简单,可以让系统定时执行指定的函数 下...

Python实现批量将word转html并将html内容发布至网站的方法

本文实例讲述了Python实现批量将word转html并将html内容发布至网站的方法。分享给大家供大家参考。具体实现方法如下: #coding=utf-8 __author__ =...

python 简单备份文件脚本v1.0的实例

整体思路 将要备份的目录列为一个列表,通过执行系统命令,进行压缩、备份。 这样关键在于构造命令并使用 os.system( )来执行,一开始使用zip 命令始终没有成功,后来发现Wind...

Python3使用TCP编写一个简易的文件下载器功能

Python3使用TCP编写一个简易的文件下载器功能

利用Python3来实现TCP协议,和UDP类似。UDP应用于及时通信,而TCP协议用来传送文件、命令等操作,因为这些数据不允许丢失,否则会造成文件错误或命令混乱。下面代码就是模拟客户端...

python中matplotlib的颜色及线条控制的示例

python中matplotlib的颜色及线条控制的示例

下次用python画图的时候选色选点都可以直接参考这边,牛逼!分享给大家,也给自己留个笔记。 参考网址: http://stackoverflow.com/questions/22408...