Skip to content

Instantly share code, notes, and snippets.

@Mohamedemad4
Last active March 15, 2021 19:08
Show Gist options
  • Save Mohamedemad4/6ff1a1f938e458e3fd0fdf79e8e1ef8f to your computer and use it in GitHub Desktop.
Save Mohamedemad4/6ff1a1f938e458e3fd0fdf79e8e1ef8f to your computer and use it in GitHub Desktop.
a usefull little class for running long running shell commands in the background and manging them in a python program or service
import os
import subprocess as sp
from multiprocessing import Process
class session_pool():
"""
Session_pool is used to run long running processes in the background
Usage:
sess_pool=session_pool()
sess_pool.run_session_process("command")
sess_pool.kill_session_process("command")
NOTICE: supply command without the & argument run_session_process() handles pushing to the background for
"""
def __init__(self):
self.process_dict={}
def session_process_thread(self,cmd):
"Internal Method where the actual thread runs"
exit_code=sp.call('({0})'.format(cmd),stdout=open('/dev/stdout', 'wb'),shell=True,executable='/bin/bash')
return self.on_exit(cmd,exit_code)
def run_session_process(self,cmd):
"""run Session Process (nonblocking)"""
proc_thread=Process(target=self.session_process_thread,args=(cmd,))
proc_thread.start()
self.process_dict.update({cmd:proc_thread})
return proc_thread
def kill_session_process(self,cmd):
proc_thread=self.process_dict[cmd]
proc_thread.terminate()
del self.process_dict[cmd]
PROC_LIST = os.popen("ps aux").read() # bash doesn't do signal forwarding; so we need to find it AND KILL IT
for sys_proc in PROC_LIST.split("\n"):
if cmd in sys_proc:
os.system("kill "+sys_proc.split(' ')[2])
def killall(self):
for proc_key in self.process_dict:
self.kill_session_process(proc_key)
def on_exit(self,cmd,exit_code):
"Runs on command exit"
if exit_code==0:
print("{0} exited with exit code 0".format(cmd))
else:
print("{0} existed with NON zero exit code ".format(cmd))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment