可以。我使用ActivePython随附的pythoncom库或可以与pywin32(适用于Windows的Python扩展)一起安装的方式来执行此操作。
这是简单服务的基本框架:
import win32serviceutilimport win32serviceimport win32eventimport servicemanagerimport socketclass AppServerSvc (win32serviceutil.Serviceframework): _svc_name_ = "TestService" _svc_display_name_ = "Test Service" def __init__(self,args): win32serviceutil.Serviceframework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): pass if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc)
你的代码将进入
main()方法中-通常带有某种无限循环,可能会通过检查在
SvcStop方法中设置的标志而中断



