i want to create window service using python to monitor notepad.exe whether it open or not. if the application not open, the service will open the notepad.exe and it will only allow one notepad.exe opened. How to make this the service launch as current user not as a system ?
here is the code:
class MonitorService(win32serviceutil.ServiceFramework):
_svc_name_ = "Monitor notepad"
_svc_display_name_ = "Monitor notepad"
_svc_description_ = "Monitors notepad executable and restarts it if it is closed."
def __init__(self, args):
username = getpass.getuser()
win32serviceutil.ServiceFramework.__init__(self, args, username=username)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
self.is_running = True
def SvcStop(self):
self.is_running = False
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
while True:
running_procs = [proc for proc in psutil.process_iter(['name']) if proc.info['name'] == 'notepad.exe']
if len(running_procs) > 1:
for proc in running_procs[1:]:
proc.kill()
elif not running_procs:
print("Notepad is not running. Starting it now...")
os.startfile(r"notepad.exe")
time.sleep(4)
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(MonitorService)