Skip to content

Instantly share code, notes, and snippets.

@wasimafser
Created April 11, 2020 11:59
import socket
import win32serviceutil
import win32service
import win32event
import servicemanager
import subprocess
import psutil
import tempfile
import configparser
import sys
import os
import time
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
class AppServerSvc(win32serviceutil.ServiceFramework):
_svc_name_ = "MistERPService"
_svc_display_name_ = "Mist ERP Service"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
app_opened = False
rc = None
temp_dir = tempfile.gettempdir()
token_txt = f"{temp_dir}{os.sep}token.txt"
app_open_initiated = False
# IF THERE IS NO TOKEN TEXT IT MEANS USER HAS NOT LOGGED-IN IN APP
while not os.path.isfile(token_txt):
if not app_open_initiated:
# IF APP IS OPENED THEN CHECK FOR FILE / APP CLOSE BEFORE LOGIN
temp_file = open(f"{temp_dir}{os.sep}app_start_log.txt", "a+")
subprocess.Popen(config.get('path', f'app_{sys.platform}'), stdout=temp_file, stderr=temp_file)
app_open_initiated = True
app_open = "app.exe" in (p.name() for p in psutil.process_iter() if p.status() == 'running')
# IF APP NOT OPEN THEN OPEN AGAIN
if not app_open:
# IF APP IS ZOMBIE TRY TO KILL
for p in psutil.process_iter():
if p.status() == 'stopped' and "app.exe" == p.name():
p.kill()
app_open_initiated = False
while rc != win32event.WAIT_OBJECT_0:
app_open = "tray.exe" in (p.name() for p in psutil.process_iter())
if app_open:
app_opened = True
else:
app_opened = False
# subprocess.Popen(TRAY_PATH)
temp_file = open(f"{temp_dir}{os.sep}tray_start_log.txt", "a+")
subprocess.Popen(config.get('path', f'tray_{sys.platform}'), stdout=temp_file, stderr=temp_file)
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
if rc == win32event.WAIT_OBJECT_0:
for proc in psutil.process_iter():
if proc.name() == 'tray.exe':
proc.kill()
with open(f"{temp_dir}{os.sep}tray_start_log.txt", "a+") as out_file:
out_file.write(f"ENDED LOOP : {rc}")
if __name__ == '__main__':
config = configparser.ConfigParser()
config.read(resource_path("service_config.ini"))
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(AppServerSvc)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(AppServerSvc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment