更新时间:2021-11-07 04:10:55
是的,你可以.我使用 ActivePython 附带的 pythoncom 库来执行此操作,或者可以安装pywin32(适用于 Windows 扩展的 Python).
Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions).
这是一个简单服务的基本框架:
This is a basic skeleton for a simple service:
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
class 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
中设置的标志而中断方法
Your code would go in the main()
method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the SvcStop
method