脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python脚本作为Windows服务启动代码详解

python脚本作为Windows服务启动代码详解

2021-01-15 00:15脚本之家 Python

本篇文章给大家分享了用python脚本写出作为Windows服务启动功能,对此有需求的朋友跟着小编一起学习下。

我们首先来看下全部代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- coding: cp936 -*-
import win32serviceutil
import win32service
import win32event
class test1(win32serviceutil.ServiceFramework):
  _svc_name_ = "test_python"
  _svc_display_name_ = "test_python"
  def __init__(self, args):
    win32serviceutil.ServiceFramework.__init__(self, args)
    self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
  def SvcStop(self):
    # 先告诉SCM停止这个过程
    self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
    # 设置事件
    win32event.SetEvent(self.hWaitStop)
  def SvcDoRun(self):
    # 等待服务被停止
    win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
if __name__=='__main__':
  win32serviceutil.HandleCommandLine(test1)

这里注意,如果你需要更改文件名,比如将win32serviceutil.HandleCommandLine(test1)中的test1更改为你的文件名,同时class也需要和你的文件名一致,否则会出现服务不能启动的问题。

延伸 · 阅读

精彩推荐