当前位置:Gxlcms > Python > 详解Python制作Windows系统服务的实例

详解Python制作Windows系统服务的实例

时间:2021-07-01 10:21:17 帮助过:91人阅读

这篇文章主要为大家详细介绍了Python制作Windows系统服务的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

最近有个Python程序需要安装并作为Windows系统服务来运行,过程中碰到一些坑,整理了一下。

Python服务类

首先Python程序需要调用一些Windows系统API才能作为系统服务,具体内容如下:

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. import time
  5. import win32api
  6. import win32event
  7. import win32service
  8. import win32serviceutil
  9. import servicemanager
  10. class MyService(win32serviceutil.ServiceFramework):
  11. _svc_name_ = "MyService"
  12. _svc_display_name_ = "My Service"
  13. _svc_description_ = "My Service"
  14. def init(self, args):
  15. self.log('init')
  16. win32serviceutil.ServiceFramework.init(self, args)
  17. self.stop_event = win32event.CreateEvent(None, 0, 0, None)
  18. def SvcDoRun(self):
  19. self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
  20. try:
  21. self.ReportServiceStatus(win32service.SERVICE_RUNNING)
  22. self.log('start')
  23. self.start()
  24. self.log('wait')
  25. win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE)
  26. self.log('done')
  27. except BaseException as e:
  28. self.log('Exception : %s' % e)
  29. self.SvcStop()
  30. def SvcStop(self):
  31. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
  32. self.log('stopping')
  33. self.stop()
  34. self.log('stopped')
  35. win32event.SetEvent(self.stop_event)
  36. self.ReportServiceStatus(win32service.SERVICE_STOPPED)
  37. def start(self):
  38. time.sleep(10000)
  39. def stop(self):
  40. pass
  41. def log(self, msg):
  42. servicemanager.LogInfoMsg(str(msg))
  43. def sleep(self, minute):
  44. win32api.Sleep((minute*1000), True)
  45. if name == "main":
  46. if len(sys.argv) == 1:
  47. servicemanager.Initialize()
  48. servicemanager.PrepareToHostSingle(MyService)
  49. servicemanager.StartServiceCtrlDispatcher()
  50. else:
  51. win32serviceutil.HandleCommandLine(MyService)

pyinstaller打包

  1. pyinstaller -F MyService.py

测试

  1. # 安装服务
  2. dist\MyService.exe install
  3. # 启动服务
  4. sc start MyService
  5. # 停止服务
  6. sc stop MyService
  7. # 删除服务
  8. sc delete MyService

以上就是详解Python制作Windows系统服务的实例的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行