使用python pywin32模块创建windows服务实例探究

 更新时间:2024年01月07日 15:03:51   作者:hyang0 生有可恋  
这篇文章主要为大家介绍了使用python pywin32模块创建windows服务实现实例探究,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

pywin32 模块

在 Windows 上,Python 没有内置的守护进程(daemon)模块。但是你可以使用 pywin32 模块来实现类似的功能。先安装 pywin32 模块,然后使用 pywin32 模块调用 windows 服务 API 创建一个后台服务。

最终效果是在 services.msc 中会多出一个自定义的服务:

安装

在给出示例代码前要先安装 pywin32 模块:

C:\> pip install pywin32

同时我们还会用到 psutil 获取进程 ID,需要安装 psutil 模块:

C:\> pip install psutil

先将进程的PID写入到指定的文件中

以下代码实现了一个后台进程,它会先将进程的PID写入到指定的文件中,然后启动一个死循环,每5秒打印一条消息代表进程还存活着。

#!python3
# Filename: pyservices.py
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import sys
import time
import psutil
def write_process_id_to_file(file_path):
    pid = str(psutil.Process().pid)
    with open(file_path, 'w') as file:
        file.write(pid)
# 进程ID
process_id_file_path = r"d:\MyPythonService.pid"
class MyService(win32serviceutil.ServiceFramework):
    _svc_name_ = "MyPythonService"
    _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):
        write_process_id_to_file(process_id_file_path)
        while self.is_alive:
            # 在这里编写你的守护进程主要逻辑
            print("Daemon is running...")
            time.sleep(5)
if __name__ == '__main__':
    if len(sys.argv) == 1:
        servicemanager.Initialize()
        servicemanager.PrepareToHostSingle(MyService)
        servicemanager.StartServiceCtrlDispatcher()
    else:
        win32serviceutil.HandleCommandLine(MyService)

以管理员身份运行 cmd,在命令行安装当前服务:

d:\> python pyservices.py install
Installing service MyPythonService
copying host exe 'C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\win32\pythonservice.exe' -> 'C:\Users\Administrator\AppData\Local\Programs\Python\Python311\pythonservice.exe'
copying helper dll 'C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\pywin32_system32\pywintypes311.dll' -> 'C:\Users\Administrator\AppData\Local\Programs\Python\Python311\pywintypes311.dll'
Service installed

services.msc查看MyPythonService

安装完后即可在 services.msc 中查看到 MyPythonService 已经注册到系统服务中了。

此时可以在服务面板中对服务进行启停,也可以在命令行中对注册的服务进行启停:

C:\> net stop MyPythonService
My Python Service 服务正在停止..
My Python Service 服务已成功停止。

C:\> net start MyPythonService
My Python Service 服务正在启动 .
My Python Service 服务已经启动成功。

同时,我们也可以在刚才的脚本执行位置对注册的服务进行启停:

d:\> python pyservices.py start
Starting service MyPythonService

d:\> python pyservices.py stop
Stopping service MyPythonService

d:\> python pyservices.py restart
Restarting service MyPythonService

除了启停服务之外,我们还能能 debug 方式运行服务。当以 debug 方式运行时,服务不会以后台方式运行,并且可以通过 ctrl+c 结束程序:

d:\> python pyservices.py debug
Debugging service MyPythonService - press Ctrl+C to stop.
Info 0x40001002 - The MyPythonService service has started.
Daemon is running...
Daemon is running...
Daemon is running...

当代码有更新时可以通过 update 命令更新服务:

d:\> python pyservices.py update
Changing service configuration
copying host exe 'C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\win32\pythonservice.exe' -> 'C:\Users\Administrator\AppData\Local\Programs\Python\Python311\pythonservice.exe'
Service updated

当不再需要运行此服务时,可以注销掉服务:

d:\> python pyservices.py remove
Removing service MyPythonService
Service removed

以上就是使用python pywin32模块创建windows服务实例探究的详细内容,更多关于python创建windows服务的资料请关注脚本之家其它相关文章!

相关文章

  • Python 四大核心数据结构之列表、字典、元组、集合

    Python 四大核心数据结构之列表、字典、元组、集合

    这段文章详细介绍了Python中的列表、元组、字典和集合四种数据结构的核心特点和适用场景,特别强调了列表的有序可修改、元组的有序不可修改、字典的键值对映射以及集合的自动去重功能,感兴趣的朋友跟随小编一起看看吧
    2026-06-06
  • python中计算一个列表中连续相同的元素个数方法

    python中计算一个列表中连续相同的元素个数方法

    今天小编就为大家分享一篇python中计算一个列表中连续相同的元素个数方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-06-06
  • Pyhton中单行和多行注释的使用方法及规范

    Pyhton中单行和多行注释的使用方法及规范

    大家都知道python中的注释有多种,有单行注释,多行注释,批量注释,中文注释也是常用的。python注释也有自己的规范,这篇文章文章中会给大家详细介绍Pyhton中单行和多行注释的使用方法及规范,有需要朋友们可以参考借鉴。
    2016-10-10
  • Python 页面解析Beautiful Soup库的使用方法

    Python 页面解析Beautiful Soup库的使用方法

    Beautiful Soup 简称 BS4(其中 4 表示版本号)是一个 Python 中常用的页面解析库,它可以从 HTML 或 XML 文档中快速地提取指定的数据,这篇文章主要介绍了springboot 集成 docsify 实现随身文档 ,需要的朋友可以参考下
    2022-09-09
  • 用实例说明python的*args和**kwargs用法

    用实例说明python的*args和**kwargs用法

    python的*args和**kwargs如何用,看了下面的例子你就清楚了。
    2013-11-11
  • Python使用MinerU的简单的示例

    Python使用MinerU的简单的示例

    MinerU是国产的一款将PDF转化为机器可读格式的工具,本文主要介绍了Python使用MinerU的简单的示例,具有一定的参考价值,感兴趣的可以了解一下
    2025-04-04
  • python 实现 mp3Play 音频播放

    python 实现 mp3Play 音频播放

    这篇文章主要介绍了python 实现 mp3Play 音频播放,文章基于python的相关资料展开详细内容,具有一定的参考价值需要的小伙伴可以参考一下
    2022-04-04
  • 在python中logger setlevel没有生效的解决

    在python中logger setlevel没有生效的解决

    今天小编就为大家分享一篇在python中logger setlevel没有生效的解决,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-02-02
  • 使用Python实现在PowerPoint文件中创建各种类型的图表

    使用Python实现在PowerPoint文件中创建各种类型的图表

    在现代商务演示和数据分析报告中,将复杂数据以可视化图表的形式呈现在 PowerPoint 幻灯片中已成为标准做法,本文将深入探讨如何使用 Python 在 PowerPoint 演示文稿中创建各种类型的图表,并对其进行精确的数据配置和样式定制,有需要的小伙伴可以了解下
    2026-03-03
  • Django创建一个后台的基本步骤记录

    Django创建一个后台的基本步骤记录

    这篇文章主要给大家介绍了关于Django创建一个后台的基本步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10

最新评论