Python implements the Process Creation Method in the windows Service, pythonwindows
This example describes how to create a process in a windows service using python. Share it with you for your reference. The specific implementation method is as follows:
Software to install: python and pywin32, I installed here are python-2.6.amd64, pywin32-217.win-amd64-py2.6
File Name: 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 ['iconpython'], dxsrv], stdin = PIPE, stdout = PIPE, stderr = PIPE, shell = False, cwd = host ['app _ path']) # create a process here. Note that the cwd parameter is indispensable and must be an absolute path # res, err = run_proc.communicate () # The above part of this function is the logic processing part, which can be customized according to your needs. However, any service in the following line of code requires win32event. waitForSingleObject (self. hWaitStop, win32event. INFINITE) run_proc.kill () # used to close the sub-process created by the Service # OS. kill (run_proc.pid, signal. SIGTERM) if _ name __= = '_ main _': win32serviceutil. handleCommandLine (DMA_WS)
Usage:
Create a service: Python dma_ws.py install
Start Service: python dma_ws.py start
Stop Service: python dma_ws.py stop
I hope this article will help you with Python programming.