Python写一个开机自启动的Windows服务

在Windows操作系统中,有一种称为服务(Service)的特殊程序类型,可以在系统启动时自动运行,并且可以在后台运行,不需要用户交互。本文将介绍如何使用Python编写一个开机自启动的Windows服务。

什么是Windows服务

Windows服务是一种在后台运行的程序类型,可以在系统启动时自动启动,无需用户登录。服务通常用于执行长期运行的任务,如网络服务、数据库服务等。

Python中的Windows服务

Python提供了win32servicewin32serviceutil模块,可以用来创建和管理Windows服务。下面我们将演示如何使用这两个模块编写一个简单的Windows服务,实现在系统启动时自动运行。

示例代码

import win32service
import win32serviceutil
import win32event
import servicemanager
import socket
import time

class PythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = "PythonService"
    _svc_display_name_ = "Python Service"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.is_running = True

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.is_running = False

    def SvcDoRun(self):
        self.is_running = True
        while self.is_running:
            hostname = socket.gethostname()
            print(f"Running on {hostname}")
            time.sleep(10)

if __name__ == '__main__':
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(PythonService)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(PythonService)

代码解释

  • PythonService类继承自win32serviceutil.ServiceFramework,重写了__init__SvcStopSvcDoRun方法。
  • __init__方法用于初始化服务对象,创建事件对象用于控制服务的停止。
  • SvcStop方法在服务停止时调用,通过设置事件来通知服务停止。
  • SvcDoRun方法是服务的主要运行逻辑,每隔10秒打印当前主机名。
  • if __name__ == '__main__':中判断服务是否需要启动,通过win32serviceutil.HandleCommandLine(PythonService)启动服务。

安装服务

要安装服务,可以使用命令行运行以下命令:

python PythonService.py install

启动服务

安装完成后,可以使用命令行启动服务:

python PythonService.py start

停止服务

停止服务可以使用命令行:

python PythonService.py stop

卸载服务

要卸载服务,可以使用命令行:

python PythonService.py remove

总结

通过本文的介绍,我们学习了如何使用Python创建一个简单的开机自启动的Windows服务。服务可以帮助我们在系统启动时自动运行一些任务,提高系统的自动化程度。希望本文对您有帮助!