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

时间:2022-09-11 00:00:11

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# 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\

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

原文链接:https://blog.csdn.net/kanghui_898/article/details/83990825