Python Win32服务自动启动

13 投票
4 回答
7343 浏览
提问于 2025-04-16 09:05

我正在写一个Python的Win32服务,下面是我代码的一部分。当我编译这个服务时,它可以正常工作,但我需要去services.msc手动启动它。

有没有什么办法,当我通过:myservice.exe install 安装服务时,它可以自动启动?

下面是我代码的一部分:

import win32serviceutil
import win32service
import win32event

class SmallestPythonService(win32serviceutil.ServiceFramework):
   _svc_name_ = "ser_name"
   _svc_display_name_ = "ser_descryption"
   #_svc_description_='ddd'
   def __init__(self, args):

      win32serviceutil.ServiceFramework.__init__(self, args)
                    self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):

       self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
       win32event.SetEvent(self.hWaitStop)

   def SvcDoRun(self):

       win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

if __name__=='__main__':

    win32serviceutil.HandleCommandLine(SmallestPythonService)

4 个回答

1

你可以使用 sc.exe 这个工具来创建服务,具体命令是 create

sc create MyPyService binPath= "C:\myservice.exe" DisplayName= "Some Python Service"

想了解更多,可以查看 微软的支持页面KB251192

win32serviceutil 里也有一个叫 InstallService() 的功能,你也许可以用得上。

2

我建议你看看这个 ActiveState 的例子。它是一个关于 win32serviceutil 的封装,演示了如何让服务自动启动。

21

使用 myservice.exe --startup=auto install 这个命令来安装服务,并设置它为自动启动。

撰写回答