使用python编写windows服务

最近测试服务器上经常发生磁盘空间不足,每次手动清除比较麻烦,所以写个windows服务定时清理下。中间也遇到过几个坑,一起记录下来。

1.python实现windows服务需要借助第三方库pywin32。可使用  pip3 命令下载。

代码如下:

# 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_ = "PythonService" #服务名
_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)

2.服务启动程序会调用SvcDoRun()。手动停止服务的时候,系统率先调用SvcStop(),将self.run置成False,SvcDoRun()跳出循环,服务停止。

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

服务运行成功!

 

最新文章

  1. C和指针 第十六章 标准函数库 本地跳转setjmp.h
  2. JDBC Driver Types
  3. XLT格式化XML那点事(C#代码中的问题解决)(二)
  4. Source Insight 3.X 标签插件v1.0发布
  5. centos7下安装nodejs
  6. hbase shell command
  7. mac和centos下git安装
  8. PostgreSQL Partitions
  9. Java检测文件是否UTF8编码
  10. java的占位符
  11. [问题解决] initAndListen: 10309 Unable to create/open lock file: /data/db/mongod.lock
  12. Matrix (二维树状数组)
  13. IE11仿真文档模式默认IE5 IE7的调整办法
  14. web端和手机端测试有什么不同
  15. 如何快速的学习selenium工具
  16. java宠物练习
  17. iframe兄弟间和iframe父子间的值传递问题
  18. Selenium自动化测试脚本中三种等待时间简介
  19. Layout-2相关代码:3列布局代码演化[一]
  20. Python:Windows8下安装BeautifulSoup

热门文章

  1. IntelliJ IDEA开发Scala代码,与java集成,maven打包编译
  2. JS-DOM ~ 03. 子节点的操作、style.样式和属性、dom元素的创建方法及操作、14个例题、主要是利用js直接控制html属性
  3. 使用vue-cli快速搭建大型单页面应用开发环境
  4. CSS基础:内联元素
  5. mysql索引类型和索引方法
  6. 逻辑运算符、三元运算符、for循环、stack(栈),heap(堆),方法区,静态域
  7. 全球性WannaCry蠕虫勒索病毒感染前后应对措施
  8. JavaScript数据结构与算法(八) 集合(ECMAScript 6中定义的类似的Set类)
  9. [C#]设计模式-工厂方法-创建型模式
  10. es6-promise源代码重点难点分析