以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程序代码放入相应位置就可以了:
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一直没法解决,就是关闭服务的同时,要把监视待机事件取消,否则退不出这个死循环。要是哪位高人看到了,希望可以指点一二。
相关文章推荐
- 以windows service方式运行Python程序的方法
- 以windows service的方式运行Python程序
- 以windows service的方式运行Python程序
- 以windows service方式运行Python程序的方法
- Windows Service开发日志四(用程序设置服务的运行状态及启动方式)
- Python Windows Service的方式运行
- python中程序运行计时的三种方式
- 让自己的C++程序(非服务程序)运行为一个windows service
- Python实现运行其他程序的四种方式实例分析
- 使用命名管道在winform程序中输出windows service运行状态
- 运行Python程序的5种方式--Python(4)
- 运行python程序的常用方式
- 使用命名管道在winform程序中输出windows service运行状态
- Python中四种运行其他程序的方式
- windows下,使用批处理文件运行python程序
- Python写Windows Service服务程序
- 运行Python程序的几种方式
- Python中四种运行其他程序的方式
- 机器学习--python程序运行时,Qt无法加载windows插件
- 使用Java Service Wrapper以windows服务的形式运行Java程序