Вот мой код:
import socket
import win32serviceutil
import win32service
import logging
import psutil
import configparser
import pyodbc
import time, threading
import win32event
logging.basicConfig(filename="ProcessMonitor.log", level=logging.INFO)
logging.info("Configured the logger")
config = configparser.ConfigParser()
config.sections()
config.read('ProcessMonitor.ini')
_host = config['ConnectionString']['host']
_user = config['ConnectionString']['user']
_password = config['ConnectionString']['passwd']
_database = config['ConnectionString']['db']
_processList = config['ProcessList']['process']
conn = pyodbc.connect(
'DRIVER={SQL Server};SERVER=' + _host + ';DATABASE=' + _database + ';UID=' + _user + ';PWD=' + _password)
cursor = conn.cursor()
StartTime = time.time()
class setInterval:
def __init__(self, interval, action):
self.interval = interval
self.action = action
self.stopEvent = threading.Event()
thread = threading.Thread(target=self.__setInterval)
thread.start()
def __setInterval(self):
nextTime = time.time() + self.interval
while not self.stopEvent.wait(nextTime - time.time()):
nextTime += self.interval
self.action()
def checkIfProcessRunning(processName):
for proc in psutil.process_iter():
try:
if processName.lower() in proc.name().lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
logging.exception('Process Not running ')
return False;
def insertProcessintoDB(runningStatus, applicationIndex):
try:
if runningStatus == 0:
sql_query = "UPDATE DB.dbo.SysMonitor Set StatusCode = 4, StatusMsg='FAILURE', LastTimestamp = " \
"GETUTCDATE() where ApplicationIndex =" + str(applicationIndex)
elif runningStatus == 1:
sql_query = "UPDATE DB.dbo.SysMonitor Set StatusCode = 1 , StatusMsg = 'OK', LastTimestamp = " \
"GETUTCDATE() where ApplicationIndex =" + str(applicationIndex)
cursor.execute(sql_query)
conn.commit()
except Exception as e:
logging.exception('Insertion Error' + str(e))
def checkProcessStatus(pname, appIndex):
isrunning = 0
if checkIfProcessRunning(pname):
print(pname + ' is running')
isrunning = 1
else:
print('Alert! ' + pname + ' is not running')
insertProcessintoDB(isrunning, appIndex)
def main():
print("*** Checking if process is running ***")
processes = _processList.split(';')
for _process_ in processes:
_processInfo_ = _process_.split(',')
processName = _processInfo_[0]
applicationIndex = _processInfo_[1]
checkProcessStatus(processName, applicationIndex)
def runmain():
inter = setInterval(30, main)
class Service(win32serviceutil.ServiceFramework):
_svc_name_ = "ProcessMonitor"
_svc_display_name_ = "ProcessMonitor"
_svc_description_ = " Python service to check running status for processes"
@classmethod
def parse_command_line(cls):
win32serviceutil.HandleCommandLine(cls)
def __init__(self, *args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
socket.setdefaulttimeout(60)
#win32serviceutil.ServiceFramework.__init__(*args)
#elf.process = Process(target=self.runmain)
def SvcStop(self):
logging.shutdown()
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
self.process.terminate()
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
def SvcDoRun(self):
self.process.start()
Service.LogMsg(Service.EVENTLOG_INFORMATION_TYPE,
Service.PYS_SERVICE_STARTED,
(self._svc_name_, ' '))
self.process.run()
if __name__ == '__main__':
Service.parse_command_line()
Когда я пытаюсь выполнить код, я вижу Файл "C: \ Users \ a \ Anaconda3 \ lib \ site-packages \ win32 \ lib \ win32serviceutil.py ", строка 523, используется sys.exit (1). Как мне go решить эту проблему? Я не вижу никаких файлов DLL тоже. Я следил за https://www.thepythoncorner.com/2018/08/how-to-create-a-windows-service-in-python/.