python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python windows services demo

python windows services demo分享

作者:小毛驴850

本文介绍了如何使用Python的pywin32库在Windows操作系统中创建和管理服务,通过一个简单的示例代码,展示了如何创建一个每隔10秒打印一条消息到日志文件的Windows服务,文章还提供了安装、启动、停止和卸载服务的命令,并附有注意事项

python windows services demo

在Windows操作系统中创建和管理服务可以通过Python实现,通常使用pywin32库。

这个库提供了访问Windows API的功能,包括创建和控制Windows服务。

下面是一个简单的示例,展示如何创建一个基本的Windows服务。

安装依赖

pip install pywin32

创建一个简单的Windows服务

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 install
python myservice.py remove

启动和停止服务

python myservice.py start
python myservice.py stop

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文