Skip to content

Instantly share code, notes, and snippets.

@stoyanovgeorge
Created February 15, 2019 12:52
Show Gist options
  • Save stoyanovgeorge/cb82b6aa5c4dd4c242bdf784dba117ec to your computer and use it in GitHub Desktop.
Save stoyanovgeorge/cb82b6aa5c4dd4c242bdf784dba117ec to your computer and use it in GitHub Desktop.
Python3 script monitoring if a process is running and logging the time when the process has stopped. It works for one or multiple instances of the same process.
#!/usr/bin/env python3
''' Script checking if a pre-defined process is running '''
import subprocess
import shlex
import time
import datetime
import psutil
import os
proc_name = "<proc_name>"
home_dir = os.getenv('HOME')
log_dir = os.path.join(home_dir, "logs")
log_name = datetime.datetime.now().strftime("%Y%m%d_process_log.txt")
log_file = os.path.join(log_dir, log_name)
def dir_creation(dir_name):
if not os.path.isdir(log_dir):
os.mkdir(dir_name)
def delete_log(log_file):
if os.path.isfile(log_file):
os.remove(log_file)
def proc_monitor(proc_name, log_file):
try:
grep_cmd = "pgrep -a " + proc_name
proc_run = subprocess.check_output(shlex.split(grep_cmd)).decode('utf-8')
proc_run = proc_run.strip().split('\n')
'''
Creating a dictionary with key the PID of the process and value
the command line
'''
proc_dict = dict(zip([i.split(' ', 1)[0] for i in proc_run],
[i.split(' ', 1)[1] for i in proc_run]))
while proc_dict:
for key, value in proc_dict.items():
if psutil.pid_exists(int(key)):
time.sleep(3)
else:
# print(f"PID: {key} of command: \"{value}\" stopped at {datetime.now().strftime('%d-%m-%Y %T')}")
with open(log_file, "a+") as log:
log.write(f"PID: {key} of command: \"{value}\" stopped at {datetime.datetime.now().strftime('%d-%m-%Y %T')}\n")
del proc_dict[key]
break
# Check if the proc_name is actually running on the machine
except subprocess.CalledProcessError as e:
print(f"The \"{proc_name}\" command isn't running on this machine")
dir_creation(log_dir)
delete_log(log_file)
proc_monitor(proc_name, log_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment