Python制作Windows系统服务

yipeiwu_com5年前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抢过年的火车票附源码

用Python抢过年的火车票附源码

前言:大家跟我一起念,Python大法好,跟着本宝宝用Python抢火车票 首先我们需要splinter 安装: pip install splinter -i http://pyp...

Django 开发环境与生产环境的区分详解

Django 开发环境与生产环境的设置 在常规的Django工程开发中,我们经常会遇到一类问题,即:本地开发环境跟远程服务器生产环境配置不一样。对于这些不同之处,以前的做法是直接修改生...

python笔记(2)

继续List: 删除元素: 复制代码 代码如下: a =[1, 2, 3, 4] a[2:3] = [] #[1, 2, 4] del a[2] #[1, 2] 清空list 复制代码...

Python3 正在毁灭 Python的原因分析

Python 3毫不费力地成为发生在Python社区里最糟糕的事。我还记得第一次使用Python的时候,我还在花大量时间在C++这块上,而Python就像是我的一次开光。我可以打开文本编...

Python对列表排序的方法实例分析

本文实例讲述了Python对列表排序的方法。分享给大家供大家参考。具体分析如下: 1、sort()函数 sort()函数使用固定的排序算法对列表排序。sort()函数对列表排序时改变了原...