Python 写windows service 及 start service 出现错误 1053:服务没有及时响应启动或控制请求

您所在的位置:网站首页 cmospwd安装失败 Python 写windows service 及 start service 出现错误 1053:服务没有及时响应启动或控制请求

Python 写windows service 及 start service 出现错误 1053:服务没有及时响应启动或控制请求

2023-12-10 07:16| 来源: 网络整理| 查看: 265

主要是记录1053这个错误,花了写时间找到解决方法。

目录

安装pywin32

实现

1053错误

安装pywin32

实现widows service 需要借助第三方模块pywin32,安装方式:打开cmd命令提示符, pip install pywin32,之后看到success说明安装成功,pip list 可以看到pywin32是否已安装。

参考

https://jingyan.baidu.com/article/6b97984de993431ca2b0bfc2.html

使用PyCharm的话还需要在PyCharm里设置 安装pywin32,否则PyCharm是无法识别pywin32 api的

参考

https://www.cnblogs.com/hackpig/p/8186214.html

实现

代码网上已经有很多了

# ZPF # encoding=utf-8 import win32timezone from logging.handlers import TimedRotatingFileHandler import win32serviceutil import win32service import win32event import os import logging import inspect import time import shutil class PythonService(win32serviceutil.ServiceFramework): _svc_name_ = "PythonService1" #服务名 _svc_display_name_ = "Clearjob" #job在windows services上显示的名字 _svc_description_ = "Clear system files" #job的描述 def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.logger = self._getLogger() self.path = 'D:\\WebSite' self.T = time.time() self.run = True def _getLogger(self): '''日志记录''' logger = logging.getLogger('[PythonService]') this_file = inspect.getfile(inspect.currentframe()) dirpath = os.path.abspath(os.path.dirname(this_file)) if os.path.isdir('%s\\log'%dirpath): #创建log文件夹 pass else: os.mkdir('%s\\log'%dirpath) dir = '%s\\log' % dirpath handler = TimedRotatingFileHandler(os.path.join(dir, "Clearjob.log"),when="midnight",interval=1,backupCount=20) 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): self.logger.info("service is run....") try: while self.run: self.logger.info('---Begin---') for path, name, file in os.walk('D:\\Website'): if path == 'D:\\Website': for IISname in name: floder = [] for i in os.listdir(os.path.join(path, IISname)): if i.isdigit(): floder.append(int(i)) if len(floder) == 0: pass elif len(floder) >= 2: # 设置保留备份 floder.sort() for x in floder[:(len(floder) - 2)]: self.logger.info("delete dir: %s" % os.path.join(os.path.join(path, IISname), str(x))) shutil.rmtree(os.path.join(os.path.join(path, IISname), str(x))) self.logger.info('---End---') time.sleep(10) except Exception as e: self.logger.info(e) time.sleep(60) def SvcStop(self): self.logger.info("service is stop....") self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) self.run = False if __name__ == '__main__': win32serviceutil.HandleCommandLine(PythonService)

代码参考

https://www.cnblogs.com/shenh/p/8931620.html

https://www.cnblogs.com/zoro-robin/p/6110188.html 

 

服务操作命令

#1.安装服务 python PythonService.py install #2.让服务自动启动 python PythonService.py --startup auto install #3.启动服务 python PythonService.py start #4.重启服务 python PythonService.py restart #5.停止服务 python PythonService.py stop #6.删除/卸载服务 python PythonService.py remove 1053错误

代码运行没有问题后,安装服务,然而start 的时候出现错误 1053:服务没有及时响应启动或控制请求(Error 1053: The service did not respond to the start or control request in a timely fashion)

试了几个网上找到的代码,都是这个现象,所以应该不是代码的问题。

后面找到解决方法:

What you need to do is to add the Python27 to SYSTEM PATH, and not to USER PATH, since as a default the python service will get installed as a 'LocalSystem' and so when it attempts to start it uses the SYSTEM PATH variable - that's why you can run it from the command prompt, your USER PATH is right.

python默认安装是作为LocalSystem,配置的是用户路径而不是环境变量,所以需要添加环境变量。

在用户变量处去掉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\

start service成功。

参考 https://stackoverflow.com/questions/8943371/cant-start-windows-service-written-in-python-win32serviceutil

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3