Link

kill_pythons.py - Killing python processes from python

Nasty cron for killing python processes:

import datetime
import os
import pytz

max_processes = 15
out = os.popen("ps -ef|grep -i python|grep -v 'Visual Studio'|grep -v grep")
counter = 0
pids = {}

def todays_date(seconds=False):
    today = datetime.datetime.now(pytz.timezone('Europe/Madrid'))
    today_str = today.strftime("%d/%m/%Y - %H:%M")
    if seconds:
      today_str = today.strftime("%d/%m/%Y - %H:%M:%S.%f")[:-3]
    return(today_str)

header = "\n\n-----------------[ START - {} ]-----------------\n".format(todays_date())
footer = "\n------------------[ END - {} ]------------------\n".format(todays_date())

print(header)

for i in list(out.readlines()):
  pid = i.lstrip(' ').split()[1]
  process = i.lstrip(' ').split()[7].split('/')[-1:][0]
  command = i.lstrip(' ').split()[8].split('/')[-1:][0]

  if len(command) < 3:
    command = process

  pids[pid] = {}
  pids[pid]['process'] = process
  pids[pid]['command'] = command


for k,v in pids.items():
	print(' * Found process {} with PID {}'.format(v['command'],k))
	if len(pids) > max_processes:
		print('** Killing {} **'.format(max_processes))
		os.kill(int(k), 9)

print(footer)

exit(0)