python windows services demo
在windows操作系统中创建和管理服务可以通过python实现,通常使用pywin32库。
这个库提供了访问windows api的功能,包括创建和控制windows服务。
下面是一个简单的示例,展示如何创建一个基本的windows服务。
安装依赖
- 首先,你需要安装
pywin32库。 - 可以通过pip来安装:
pip install pywin32
创建一个简单的windows服务
- 以下是一个基本的windows服务示例代码。
- 该服务会每隔10秒打印一条消息到日志文件。
import win32serviceutil
import win32service
import win32event
import servicemanager
import time
import logging
# 配置日志记录
logging.basicconfig(
filename='c:\\path_to_your_log_file\\my_service.log',
level=logging.debug,
format='%(asctime)s %(levelname)-8s %(message)s'
)
class myservice(win32serviceutil.serviceframework):
_svc_name_ = "mypythonservice" # 服务名称
_svc_display_name_ = "my python service" # 服务显示名称
_svc_description_ = "this is a demo service using python." # 服务描述
def __init__(self, args):
win32serviceutil.serviceframework.__init__(self, args)
self.hwaitstop = win32event.createevent(none, 0, 0, none)
self.is_alive = true
def svcdorun(self):
servicemanager.logmsg(servicemanager.eventlog_information_type,
servicemanager.pys_service_started,
(self._svc_name_, ''))
self.main()
def svcstop(self):
self.reportservicestatus(win32service.service_stop_pending)
win32event.setevent(self.hwaitstop)
self.is_alive = false
def main(self):
while self.is_alive:
logging.info('service is running...')
time.sleep(10) # 每隔10秒执行一次
if __name__ == '__main__':
win32serviceutil.handlecommandline(myservice)注意事项
修改日志路径:请确保将filename='c:\\path_to_your_log_file\\my_service.log'替换为你希望存储日志文件的实际路径。
安装服务:
- 将上述代码保存为一个python文件(例如
myservice.py)。 - 打开命令提示符(管理员权限),然后导航到包含你的python脚本的目录。
- 使用以下命令安装服务:
python myservice.py install
- 如果需要卸载服务,可以使用:
python myservice.py remove
启动和停止服务:
- 可以通过命令提示符使用以下命令启动服务:
python myservice.py start
- 停止服务:
python myservice.py stop
- 也可以通过windows服务管理器(
services.msc)来管理服务。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论