python实现编写windows服务
使用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


服务运行成功!
python实现编写windows服务的更多相关文章
- C#编写windows服务
项目要求: 数据库用有一张表,存放待下载文件的地址,服务需要轮训表将未下载的文件下载下来. 表结构如下: 过程: VS--文件-->新建项目-->windows-->windows服 ...
- 使用C语言编写windows服务一般框架
原文:使用C语言编写windows服务一般框架 编写windows服务和编写windows应用程序一样,有一些回调函数必须填写且向windows 服务管理器(service manager)进行注册, ...
- C#编写Windows 服务
C#编写Windows 服务 Microsoft Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时 ...
- C# 编写windows服务及服务的安装、启动、删除、定时执行任务
一.编写windows服务 1.VS2017 - 创建服务Myservice 2.创建好项目之后 --- >> 双击 Service1.cs ---- >> 出现一个设计 ...
- c# 编写windows 服务,并制作安装包
对服务的认识有很多个阶段. 第一阶段:当时还在用c++,知道在一个进程里while(True){},然后里面做很多很多事情,这就叫做服务了,界面可能当时还用Console控制台程序. 第二阶段:知道了 ...
- 手把手教用C#编写Windows服务 并控制服务 安装、启动、停止、卸载
Windows服务 Microsoft Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时自动启动, ...
- 第八篇--编写Windows服务
编写service服务参考网址:https://blog.csdn.net/nodeathphoenix/article/details/24181509 vc获得显示器状态(捕获息屏.亮屏网址):h ...
- 编写Windows服务疑问1:操作过程
Windows 服务开发平时不太受人关注,毕竟那是高大上的项目类型,平常需求也用不上,很多老掉牙的家伙也只知有WinForm,仍不知有WPF,更别说Windows 服务了,正如陶渊明所写的,“不知有汉 ...
- 在python中编写socket服务端模块(二):使用poll或epoll
在linux上编写socket服务端程序一般可以用select.poll.epoll三种方式,本文主要介绍使用poll和epoll编写socket服务端模块. 使用poll方式的服务器端程序代码: i ...
随机推荐
- 分布式服务框架HSF
最近在读阿里巴巴中台战略思想与架构这本书,so和大家分享一些我get到的东东. HSF是阿里巴巴内部的分布式服务框架,这个大家都很熟悉了,先上一张HSF的工作原理图: 这个图说明了HSF框架中每个组件 ...
- ribbon 详解
ribbon 详解 1. 顶层架构 2. 简单的示例:使用ResourceTemplate方式 @Test public void testGroup(){ HttpResourceGroup htt ...
- 测试驱动开发实践4————testSave之新增文档分类
[内容指引] 1.确定"新增文档分类"的流程及所需的参数 2.根据业务规则设计测试用例 3.为测试用例赋值并驱动开发 一.确定"新增文档分类"的流程及所需的参数 ...
- Qt QFile文件读写
QFile 需要添加 #Include <QFile> 集成至QIODevice 打开一个文件有3种方式QIODevice::(ReadOnly/WriteOnly/ReadWrite) ...
- POJ-3259 Wormholes---SPFA判断有无负环
题目链接: https://vjudge.net/problem/POJ-3259 题目大意: 农夫约翰在探索他的许多农场,发现了一些惊人的虫洞.虫洞是很奇特的,因为它是一个单向通道,可让你进入虫洞的 ...
- HTC Vive 叠影器无法创建设备
今天使用笔记本电脑打开SteamVR发生错误:SteamVR启动失败,"Shared IPC Compositor Connected Fail(306)",然后启动失败,在UI界 ...
- MyBatis(2)——MyBatis 深入学习
编写日志输出环境配置文件 在开发过程中,最重要的就是在控制台查看程序输出的日志信息,在这里我们选择使用 log4j 工具来输出: 准备工作: 将[MyBatis]文件夹下[lib]中的 log4j 开 ...
- SQL学习之查询
查询实例: 1.创建数据库并使用: create database school; use school; 2.创建表并插入内容: create table student( Sno char(9) ...
- [Codeforces 864D]Make a Permutation!
Description Ivan has an array consisting of n elements. Each of the elements is an integer from 1 to ...
- [Vijos 2024]无向图最短路径
Description 无向图最短路径问题,是图论中最经典也是最基础的问题之一.本题我们考虑一个有 $n$ 个结点的无向图 $G$.$G$ 是简单完全图,也就是说 $G$ 中没有自环,也没有重边,但任 ...