簡體   English   中英

Python可執行文件作為Windows服務

[英]Python executable as Windows Service

我知道在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"

我最終找到了我問題的答案。 實際上,要求提供服務。 大多數成為服務的腳本或程序在代碼上方都有一個包裝層,用於管理對這些要求的處理。 該包裝器最終調用開發人員的代碼,並以不同類型的狀態向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服務是有要求的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM