python實現在windows服務中建立進程的方法

來源:互聯網
上載者:User
本文執行個體講述了python實現在windows服務中建立進程的方法。分享給大家供大家參考。具體實現方法如下:

需要安裝的軟體:python和pywin32,我這裡裝的分別是python-2.6.amd64、pywin32-217.win-amd64-py2.6

檔案名稱:dma_ws.py

#!pythonimport win32serviceutil import win32service import win32eventimport os from subprocess import Popen, PIPEimport jsonimport signalrun_proc = Noneclass DMA_WS(win32serviceutil.ServiceFramework):  _svc_name_ = "DMA_WS" _svc_display_name_ = "DMA_WS" 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):  f = file('C:/DXMonitorSystem/dma.conf')  host = json.load(f)  f.close()  dxsrv = os.path.join(host['app_path'], 'DXHttpServer.py')  run_proc = Popen([host['ironpython'], dxsrv],      stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False,      cwd=host['app_path'])      #這裡建立進程,注意cwd參數必不可少且要是絕對路徑  #res, err = run_proc.communicate()  #這個函數內的上面部分都是邏輯處理的部分,可以根據自己的需求訂製,但下面這行代碼任何服務都需要  win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)   run_proc.kill() # 用於關閉服務所建立的子進程  #os.kill(run_proc.pid, signal.SIGTERM)if __name__=='__main__': win32serviceutil.HandleCommandLine(DMA_WS)

使用方法:

建立服務:Python dma_ws.py install

開始服務:python dma_ws.py start

停止服務:python dma_ws.py stop

希望本文所述對大家的Python程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.