以Windows Service的方式运行Python程序


Python程序代码

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

由于运行时Python程序的控制台窗口一直在那儿,看着有点碍事儿。于是乎想到要是能把他以windowsservice的方式运行,就像其他在windows服务管理器里的程序一样。

最终,在"PythonProgrammingOnWin32"byMarkHammond)这本书里找到了相关介绍,它里
面有一个简单的模版,把Python程序代码放入相应位置就可以了:

  1. #SmallestService.py  
  2. #  
  3. #AsampledemonstratingthesmallestpossibleservicewritteninPython.  
  4.  
  5. importwin32serviceutil  
  6. importwin32service  
  7. importwin32event  
  8.  
  9. classSmallestPythonService(win32serviceutil.ServiceFramework):  
  10. _svc_name_="SmallestPythonService" 
  11. _svc_display_name_="ThesmallestpossiblePythonService" 
  12. def__init__(self,args):  
  13. win32serviceutil.ServiceFramework.__init__(self,args)  
  14. #Createaneventwhichwewillusetowaiton.  
  15. #The"servicestop"requestwillsetthisevent.  
  16. self.hWaitStop=win32event.CreateEvent(None,0,0,None)  
  17.  
  18. defSvcStop(self):  
  19. #Beforewedoanything,telltheSCMwearestartingthestopprocess.  
  20. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)  
  21. #Andsetmyevent.  
  22. win32event.SetEvent(self.hWaitStop)  
  23.  
  24. defSvcDoRun(self):
  25. #把你的程序代码放到这里就OK了
    win32event.WaitForSingleObject(self.hWaitStop,win32event.INFINITE)

    if__name__=='__main__':
    win32serviceutil.HandleCommandLine(SmallestPythonService)
    #括号里的名字可以改成其他的,必须与class名字一致; 

接下来,只要安装一下服务,cmd下运行:SmallestService.pyinstall就行了。

这样,你就可以在windows服务管理器里找到一个名叫"ThesmallestpossiblePythonService"的服务了,设成自动启动,就会开机自动启动并且一直在后台运行了。眼不见心不烦,)

不过,这样虽然达到目的了,但还是发现个小问题,就是要是想停止该服务,关闭的进度条就愣在那里不动了,必须在进程管理器里把pythonservice.exe关掉才行,这个bug一直没法解决,就是关闭服务的同时,要把监视待机事件取消,否则退不出这个死循环。要是哪位高人看到了,希望可以指点一二。

  1. 浅谈Python和C#中的Run As代码实现方式
  2. 脚本语言排行榜 PHP、Ruby和Python领先
  3. Python选择Mercurial Hg版本控制系统
  4. 在Python中解决中英文混杂出错的问题
  5. 使用Oracle数据库实现Python数据持久

评论关闭