您的位置:首页 > 编程语言 > Python开发

以Windows Service的方式运行Python程序

2012-08-02 17:12 471 查看
本文将介绍如何以Windows Service的方式运行Python程序,语句很简单,要用到Tim Golden编写的wmi.py 和 Mark Hammond的win32 extensions for Python ,两个缺一不可。

importwmi
importos
c=wmi.WMI()
watcher=c.Win32_PowerManagementEvent.watch_for(EventType=7)#监视待机事件的语句;
whileTrue:
os.system("kdlj.vbs")#运行“连接宽带“的程序,这里还是用了上次那位仁兄的vbs代码;
watcher()

由于运行时Python程序的控制台窗口一直在那儿,看着有点碍事儿。于是乎想到要是能把他以windowsservice的方式运行,就像其他在windows服务管理器里的程序一样。最终,在"PythonProgrammingOnWin32"(byMarkHammond)这本书里找到了相关介绍,它里
面有一个简单的模版,把Python程序代码放入相应位置就可以了:
#SmallestService.py  
#  
#AsampledemonstratingthesmallestpossibleservicewritteninPython.  
 
importwin32serviceutil  
importwin32service  
importwin32event  
 
classSmallestPythonService(win32serviceutil.ServiceFramework):  
_svc_name_="SmallestPythonService" 
_svc_display_name_="ThesmallestpossiblePythonService" 
def__init__(self,args):  
win32serviceutil.ServiceFramework.__init__(self,args)  
#Createaneventwhichwewillusetowaiton.  
#The"servicestop"requestwillsetthisevent.  
self.hWaitStop=win32event.CreateEvent(None,0,0,None)  
 
defSvcStop(self):  
#Beforewedoanything,telltheSCMwearestartingthestopprocess.  
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)  
#Andsetmyevent.  
win32event.SetEvent(self.hWaitStop)  
 
defSvcDoRun(self):
#把你的程序代码放到这里就OK了
win32event.WaitForSingleObject(self.hWaitStop,win32event.INFINITE)if__name__=='__main__':
win32serviceutil.HandleCommandLine(SmallestPythonService)
#括号里的名字可以改成其他的,必须与class名字一致;
接下来,只要安装一下服务,cmd下运行:SmallestService.pyinstall就行了。这样,你就可以在windows服务管理器里找到一个名叫"ThesmallestpossiblePythonService"的服务了,设成自动启动,就会开机自动启动并且一直在后台运行了。(眼不见心不烦,)不过,这样虽然达到目的了,但还是发现个小问题,就是要是想停止该服务,关闭的进度条就愣在那里不动了,必须在进程管理器里把pythonservice.exe关掉才行,这个bug一直没法解决,就是关闭服务的同时,要把监视待机事件取消,否则退不出这个死循环。要是哪位高人看到了,希望可以指点一二。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: