Python注册Windows服务

在Windows操作系统上运行的程序可以作为Windows服务来运行。通过将Python程序注册为Windows服务,可以使其在系统启动时自动运行,并且以后台服务的方式持续运行。

本文将介绍如何使用Python的win32service模块来注册和管理Windows服务。我们将从安装必要的库开始,然后演示如何编写一个简单的Python程序并将其注册为Windows服务。

准备工作

首先,我们需要安装pywin32库,它是Python与Windows API交互的库。可以使用pip命令来安装它:

pip install pywin32

编写一个简单的Windows服务

让我们编写一个简单的Python程序作为我们要注册的Windows服务。假设我们要编写一个服务,每隔5秒向日志文件写入一条日志。

下面是一个简单的示例代码:

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import os
import sys
import time

class MyService(win32serviceutil.ServiceFramework):
    _svc_name_ = 'MyService'
    _svc_display_name_ = 'My Service'

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)
        self.is_alive = True

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

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        self.main()

    def main(self):
        while self.is_alive:
            # 写入日志
            with open('log.txt', 'a') as f:
                f.write('Logging...\n')
            time.sleep(5)

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

上述代码定义了一个名为MyService的类,它继承自win32serviceutil.ServiceFramework类。MyService类包含了一些必要的方法,包括SvcStopSvcDoRunmain方法。

  • SvcStop方法在服务停止时被调用,它通过设置事件hWaitStop来通知服务停止。
  • SvcDoRun方法是服务的入口点,它在服务开始运行时被调用。
  • main方法是我们实际的服务逻辑,它会循环地向日志文件写入日志。

注册Windows服务

现在我们已经编写了一个简单的Windows服务程序,下面是如何将其注册为Windows服务。

打开命令提示符,并以管理员身份运行以下命令:

python <路径>\myservice.py install

其中,<路径>是你的Python脚本所在的路径。

运行该命令后,服务将会被注册到Windows服务列表中。你可以在Windows服务管理器中找到并管理它。

管理Windows服务

  • 启动服务:

    python <路径>\myservice.py start
    
  • 停止服务:

    python <路径>\myservice.py stop
    
  • 卸载服务:

    python <路径>\myservice.py remove
    

总结

本文介绍了如何使用win32service模块将Python程序注册为Windows服务,并以后台服务的方式持续运行。我们编写了一个简单的服务程序,并演示了如何注册和管理该服务。

通过将Python程序注册为Windows服务,可以使其在系统启动时自动运行,并且以后台服务的方式持续运行,极大地方便了程序的部署和运维。

参考链接

  1. [Python for Windows Extensions](
  2. [Python Win32 Extensions Documentation](