Python 在Windows中如何将Python脚本作为服务运行

Python 在Windows中如何将Python脚本作为服务运行

在本文中,我们将介绍如何在Windows操作系统中将Python脚本作为服务运行。将Python脚本作为服务运行可以使其在后台持续运行,无需用户登录,提供更好的稳定性和可靠性。

阅读更多:Python 教程

什么是Windows服务?

Windows服务是在Windows操作系统后台运行的程序。它们可以在系统启动时自动运行,无需用户登录,即使用户注销或关闭命令行窗口,服务仍然会继续运行。服务通常在Windows操作系统中执行一些持续运行的任务,如网络服务、数据库服务等。

使用pywin32库创建Python服务

在Windows中,我们可以使用pywin32库来将Python脚本作为服务运行。pywin32库提供了与Windows API交互的功能,使我们可以在Python中创建、注册和管理Windows服务。

首先,我们需要安装pywin32库。在命令行中执行以下命令:

pip install pywin32
Bash

接下来,让我们来编写一个简单的Python脚本作为示例。假设我们的脚本名为my_script.py,内容如下:

import time

while True:
    print("Service is running...")
    time.sleep(5)
Python

以上示例脚本会每隔5秒打印一次”Service is running…”。

下面是将脚本作为服务运行的步骤:

Step 1: 导入所需模块

import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import sys
import os
import traceback
Python

Step 2: 定义服务类

class MyService(win32serviceutil.ServiceFramework):
    _svc_name_ = 'MyService'
    _svc_display_name_ = 'My Python 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):
        try:
            import my_script  # 导入我们的脚本
            while self.is_alive:
                pass
        except Exception as e:
            traceback.print_exc(file=sys.stdout)
Python

Step 3: 将服务注册为Windows服务

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

现在,我们可以将以上代码保存为一个名为my_service.py的文件。然后,在命令行中执行以下命令将其注册为服务:

python my_service.py install
Bash

注册成功后,我们可以在Windows服务列表中看到我们的服务My Python Service

Step 4: 启动和管理服务

可以使用以下命令来启动、停止和管理我们的服务:

python my_service.py start   # 启动服务
python my_service.py stop    # 停止服务
python my_service.py remove  # 从系统中移除服务
Bash

这样,我们就成功地将Python脚本作为一个Windows服务运行起来了。

总结

本文介绍了如何将Python脚本作为服务在Windows操作系统中运行。只需使用pywin32库,我们可以轻松地创建、注册和管理Windows服务,实现Python脚本的后台持续运行。希望本文能帮助你在Windows中更好地利用Python脚本运行服务。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册