作为Windows服务的Python可执行文件

2024-04-19 15:50:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道StackOverflow上也有类似的话题,但没有一个和我有同样的问题。大多数问题都是问如何从Python启动服务。我有一个创建服务的.bat文件,它使用的是我使用py2exe创建的PythonFile.exe。我得到错误“错误启动服务。服务没有及时响应启动或控制请求”。服务不运行,但我在ProcessManager进程中看到可执行文件。

可执行文件作为服务是否有特定要求?我的可执行文件只是一个TCP服务器,在互斥锁被解锁之前一直在休眠(使用互斥锁)。

我的.bat文件。。。

net stop "FabulousAndOutrageousOinkers"
%SYSTEMROOT%\system32\sc.exe delete "FabulousAndOutrageousOinkers"
%SYSTEMROOT%\system32\sc.exe create "FabulousAndOutrageousOinkers" binPath= "%CD%\FabulousAndOutrageousOinkers.exe" start= auto
net start "FabulousAndOutrageousOinkers"

Tags: 文件可执行文件net错误stackoverflowexestartsc
1条回答
网友
1楼 · 发布于 2024-04-19 15:50:32

我最终找到了我问题的答案。事实上,服务是有要求的。大多数成为服务的脚本或程序在代码之上都有一个包装层来管理这些需求的处理。这个包装器最终调用开发人员的代码,并用不同类型的状态向windows服务发送信号。开始、停止等。。。

import win32service  
import win32serviceutil  
import win32event  

class Service(win32serviceutil.ServiceFramework):  
    # you can NET START/STOP the service by the following name  
    _svc_name_ = "FabulousAndOutrageousOinkers"  
    # this text shows up as the service name in the Service  
    # Control Manager (SCM)  
    _svc_display_name_ = "Fabulous And Outrageous Oinkers"  
    # this text shows up as the description in the SCM  
    _svc_description_ = "Truly truly outrageous"  

    def __init__(self, args):  
        win32serviceutil.ServiceFramework.__init__(self,args)  
        # create an event to listen for stop requests on  
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)  

    # core logic of the service     
    def SvcDoRun(self):  
        import servicemanager
        self.ReportServiceStatus(win32service.SERVICE_START_PENDING)  

        self.start() 
        rc = None  

        # if the stop event hasn't been fired keep looping  
        while rc != win32event.WAIT_OBJECT_0:  
            # block for 5 seconds and listen for a stop event  
            rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)

        self.stop()

    # called when we're being shut down      
    def SvcStop(self):  
        # tell the SCM we're shutting down  
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)  
        # fire the stop event  
        win32event.SetEvent(self.hWaitStop)

    def start(self):
       try:
          file_path = "FabulousAndOutrageousOinkers.exe"
          execfile(file_path)             #Execute the script
       except:
          pass

    def stop(self):
      pass

if __name__ == '__main__':  
    win32serviceutil.HandleCommandLine(Service)

我从http://www.chrisumbel.com/article/windows_services_in_python找到这个模板。这段代码仍然有一些问题,因为我得到错误“错误启动服务:服务没有及时响应启动或控制请求”,但它仍然回答了我的问题。实际上,可执行文件需要成为Windows服务。

相关问题 更多 >