详解python制作windows系统服务的实例

这篇文章主要为大家详细介绍了python制作windows系统服务的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

最近有个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制作windows系统服务的实例的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类