Python 脚本注册为Windows Service
这部分内容就如同标题所讲的,其他的也不说了,直接上代码吧
需要说明的是,此代码在我的Win10 下可以正常使用,而在windows server 2008没有运行成功。
如果出现拒绝访问的错误,请使用管理员权限打开cmd窗口即可。
Run Python scripts as a service example (ryrobes.com)
Usage : python aservice.py install (or / then start, stop, remove)
import win32service
import win32serviceutil
import win32api
import win32con
import win32event
import win32evtlogutil
import os, sys, string, time
class aservice(win32serviceutil.ServiceFramework):
svc_name = "MyServiceShortName"
svc_display_name = "My Serivce Long Fancy Name!"
svc_description = "THis is what my crazy little service does - aka a DESCRIPTION! WHoa!"
def init(self, args):
win32serviceutil.ServiceFramework.init(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
import servicemanager
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self.svc_name, ''))
该函数下面直接填写你需要执行的任务,形式是一个无限循环
def ctrlHandler(ctrlType):
return True
if name == 'main':
win32api.SetConsoleCtrlHandler(ctrlHandler, True)
win32serviceutil.HandleCommandLine(aservice)

浙公网安备 33010602011771号