windows service运行Python相关操作技巧分享

开发 后端
在windows service运行Python的过程中,有许多应用技巧需要我们及时的掌握,才能很好的来操作这一过程。在这里将会对此做一个详细介绍。

我们今天将要为大家介绍的是有关windows service运行Python的一些应用技巧。相信用过Python这一编程语言的朋友们都会发现这一门功能强大,简单易用的程序语言,可以帮助我们轻松的实现许多功能需求。

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

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

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

  1. # SmallestService.py  
  2. #  
  3. # A sample demonstrating the smallest possible service written in Python.  
  4. import win32serviceutil  
  5. import win32service  
  6. import win32event  
  7. class SmallestPythonService(win32serviceutil.ServiceFramework):  
  8. _svc_name_ = "SmallestPythonService" 
  9. _svc_display_name_ = "The smallest possible Python Service" 
  10. def __init__(self, args):  
  11. win32serviceutil.ServiceFramework.__init__(self, args)  
  12. # Create an event which we will use to wait on.  
  13. # The "service stop" request will set this event.  
  14. self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)  
  15. def SvcStop(self):  
  16. # Before we do anything, tell the SCM we are starting the stop process.  
  17. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)  
  18. # And set my event.  
  19. win32event.SetEvent(self.hWaitStop)  
  20. def SvcDoRun(self):  
  21. # 把你的程序代码放到这里就OK了  
  22. win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)  
  23. if __name__=='__main__':  
  24. win32serviceutil.HandleCommandLine(SmallestPythonService)   
  25. # 括号里的名字可以改成其他的,必须与class名字一致; 

接下来,只要安装一下服务,cmd下运行:SmallestService.py install 就行了。这样,你就可以在windows服务管理器里找到一个名叫"The smallest possible Python Service"的服务了,设成自动启动,就会开机自动启动并且一直在后台运行了。(眼不见心不烦,)

不过,这样虽然达到windows service运行Python的目的了,但还是发现个小问题,就是要是想停止该服务,关闭的进度条就愣在那里不动了,必须在进程管理器里把pythonservice.exe关掉才行。

【编辑推荐】

  1. Python下划线在实际应用中功能体现
  2. 常用Python应用技巧内容分析
  3. 安装Python简单操作方法分享
  4. Python Helloworld程序简单实现
  5. Python Class正确应用代码示例剖析
责任编辑:曹凯 来源: 博客园
相关推荐

2010-01-25 18:33:35

Android键盘操作

2009-12-10 17:27:39

PHP操作Cookie

2010-01-28 14:12:20

Android Act

2010-01-06 17:02:28

.Net Framew

2009-12-10 16:35:08

PHP操作文章列表

2010-03-03 16:57:28

Python字符

2010-03-04 14:39:52

Python读取输入值

2010-01-13 10:25:30

VB.NET文件夹操作

2010-03-03 10:10:33

Python实现Soc

2009-07-02 16:36:58

Python程序

2010-01-13 15:33:40

VB.NET菜单项目

2009-12-29 16:08:41

Silverlight

2010-02-22 17:58:06

WCF异步上传

2010-03-03 13:45:08

Python查找重复文

2010-01-15 15:10:43

VB.NET Stri

2010-02-24 11:22:04

WCF方法重载

2010-01-28 10:55:14

Android电源管理

2009-12-30 13:37:24

Silverlight

2009-12-30 10:25:03

Silverlight

2010-01-04 14:49:30

Silverlight
点赞
收藏

51CTO技术栈公众号