windows service运行Python相关操作技巧有哪些

发布时间:2021-11-01 17:52:58 作者:小新
来源:亿速云 阅读:156

这篇文章主要为大家展示了“windows service运行Python相关操作技巧有哪些”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“windows service运行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)这本书里找到了相关介绍,它里面有一个简单的模版,把程序代码放入相应位置就可以了:

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

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

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

以上是“windows service运行Python相关操作技巧有哪些”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. SharePoint 排错:添加Windows Cluste
  2. Windows Server 2016-命令行方式管理Windows服务

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

windows service python

上一篇:Python PDB有什么用

下一篇:Python大小写如何应用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》