Python制作Windows系统服务

yipeiwu_com6年前Python基础

最近有个Python程序需要安装并作为Windows系统服务来运行,过程中碰到一些坑,整理了一下。

Python服务类

首先Python程序需要调用一些Windows系统API才能作为系统服务,具体内容如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import time

import win32api
import win32event
import win32service
import win32serviceutil
import servicemanager


class MyService(win32serviceutil.ServiceFramework):

  _svc_name_ = "MyService"
  _svc_display_name_ = "My Service"
  _svc_description_ = "My Service"

  def __init__(self, args):
    self.log('init')
    win32serviceutil.ServiceFramework.__init__(self, args)
    self.stop_event = win32event.CreateEvent(None, 0, 0, None)

  def SvcDoRun(self):
    self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
    try:
      self.ReportServiceStatus(win32service.SERVICE_RUNNING)
      self.log('start')
      self.start()
      self.log('wait')
      win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
      self.log('done')
    except BaseException as e:
      self.log('Exception : %s' % e)
      self.SvcStop()

  def SvcStop(self):
    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
    self.log('stopping')
    self.stop()
    self.log('stopped')
    win32event.SetEvent(self.stop_event)
    self.ReportServiceStatus(win32service.SERVICE_STOPPED)

  def start(self):
    time.sleep(10000)

  def stop(self):
    pass

  def log(self, msg):
    servicemanager.LogInfoMsg(str(msg))

  def sleep(self, minute):
    win32api.Sleep((minute*1000), True)

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

pyinstaller打包

pyinstaller -F MyService.py

测试

# 安装服务
dist\MyService.exe install

# 启动服务
sc start MyService

# 停止服务
sc stop MyService

# 删除服务
sc delete MyService

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中import与from方法总结(推荐)

一、模块&包简介 模块:所谓模块就是一个.py文件,用来存放变量,方法的文件,便于在其他python文件中导入(通过import或from)。 包(package): 包是更大的组织单位...

使用Python编写一个在Linux下实现截图分享的脚本的教程

引子 Linux下不支持QQ等功能丰富的IM,虽然可以通过wine运行QQ2012,但是还是喜欢在gtalk群中聊天,gtalk群不支持图片方式,这就要靠我们大家自己来解决了,eleve...

python 矩阵增加一行或一列的实例

python 矩阵增加一行或一列的实例

矩阵增加行 np.row_stack() 与 np.column_stack() import numpy as np a = np.array([[4, 4,], [5, 5]])...

Python实现微信消息防撤回功能的实例代码

Python实现微信消息防撤回功能的实例代码

微信(WeChat)是腾讯公司于2011年1月21日推出的一款社交软件,8年时间微信做到日活10亿,日消息量450亿。在此期间微信也推出了不少的功能如:“摇一摇”、“漂流瓶”、“朋友圈”...

ZABBIX3.2使用python脚本实现监控报表的方法

ZABBIX3.2使用python脚本实现监控报表的方法

如下所示: #!/usr/bin/python #coding:utf-8 import MySQLdb import time,datetime #zabbix数据库...