利用python 建立windows服务的一点总结

2022/2/19 7:13:32

本文主要是介绍利用python 建立windows服务的一点总结,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

最新想通过python写个windows服务 在系统后台处理一些事情,网上查了也写资料,总体看差别不大,都是先pip  install pywin32 这个模块  ,然后新建一个类,写代码,这部分内容参考网上的帖子就可以,这里我要总结的地方是,在按照网上帖子写好服务后 显示碰到了 注册服务不成功的问题,这个问题按照 博客园 的  三只松鼠  这位博主的总结内容解决了,但是注册成功后,在start服务后  服务总是启动不起来,在服务管理里 用手动也启动不起来,后来 注意到在安装服务命令执行后,控制台会给出相关提示

按照这个提示 我把我写的服务py文件放在这个目录   然后在这个目录 运行cmd    再按照服务  启动服务  都没有问题了

我的代码也一并列出来

 1 import logging
 2 import logging.handlers
 3 import datetime
 4 import time
 5 
 6 import win32timezone
 7 import win32serviceutil
 8 import win32service
 9 import win32event
10 
11 
12 class PythonService(win32serviceutil.ServiceFramework):
13     _svc_name_ = "PythonService"  # 服务名称
14     _svc_display_name_ = "Python_Service"  # 在windows services上显示的名字
15     _svc_description_ = "get codesys opcua values"  # 通过opcua获取codesys的数据
16 
17     def __init__(self, args):
18         win32serviceutil.ServiceFramework.__init__(self, args)
19         self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
20         self.logger = self._getLogger()
21         self.runFlag = True
22 
23     def _getLogger(self):
24         logger = logging.getLogger('opc_log')
25         logger.setLevel(logging.DEBUG)
26 
27         rf_handler = logging.handlers.TimedRotatingFileHandler('D:\opc_gpio.log', when='midnight', interval=1,
28                                                                backupCount=7, atTime=datetime.time(0, 0, 0, 0))
29         rf_handler.setFormatter(logging.Formatter("%(asctime)s--%(name)s--%(levelname)s--%(message)s"))
30         logger.addHandler(rf_handler)
31         return logger
32 
33     def SvcDoRun(self):
34         import  time
35         #self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
36         self.logger.info("服务运行了")
37         try:
38             while self.runFlag:
39                 self.logger.info("开始循环了")
40                 time.sleep(10)
41         except Exception as e:
42             self.logger.info(e)
43             time.sleep(60)
44 
45     def SvcStop(self):
46         self.logger.info("服务停止")
47         self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
48         win32event.SetEvent(self.hWaitStop)
49         self.runFlag = False
50 
51 
52 if __name__ == '__main__':
53     win32serviceutil.HandleCommandLine(PythonService)

我这里也抄一部分  三只松鼠  博主的内容  写在这里 给自己做个提示,

3.然后将服务安装到windows
管理员运行cmd,输入如下命令:

复制代码
#安装服务
python Clearjob.py install

#开启服务
python Clearjob.py start

#停止服务
python Clearjob.py stop

#移除服务
python Clearjob.py remove
复制代码

 

异常解决方法

  1.开启服务的时候会出现报错“The service did not respond to the start or control request in a timely fashion”,意思是“服务没有及时响应启动或控制请求”。

 

 2.解决方案:将Python36\Lib\site-packages\win32路径下的pythonservice.exe注册一下。

                   注册命令:pythonservice.exe /register

 

3.这很尴尬。。。缺少pywintypes36.dll。找下,在Python36\Lib\site-packages\pywin32_system32路径。

  解决方法:设置到环境变量或者将此dll copy到Python36\Lib\site-packages\win32。

  注册完后执行python Clearjob.py start

服务运行成功!



这篇关于利用python 建立windows服务的一点总结的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程