Python 脚本注册为Windows Service

时间:2023-03-08 22:21:38
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) # Done! Lets go out and get some dinner, bitches!

参考####