Skip to content

Instantly share code, notes, and snippets.

@jamiembrown
Created January 24, 2014 17:33
Show Gist options
  • Save jamiembrown/8602117 to your computer and use it in GitHub Desktop.
Save jamiembrown/8602117 to your computer and use it in GitHub Desktop.
Check if a process is running, kill it or start it
# Check if a process is running or not
def is_proc_running(proc_name):
command = 'ps aux | grep -v grep | grep -v /bin/sh | grep ' + proc_name
output = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).communicate()[0]
if len(output)==0:
return False
else:
return True
# Run a process, printing all of its output to stdout
def run_proc(proc_path):
command = proc_path + ' 2>&1 &'
output = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).pid
return output
# Force kill a process by name
def killproc(proc_name):
# Get the pid of the command
command = 'ps aux | grep -v grep | grep -v /bin/sh | grep ' + proc_name
output = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True).communicate()[0]
if len(output)==0:
print "Could not kill %s: No process found" % proc_name
return False
else:
# Send it a kill signal
sep = re.compile('[\s]+')
output_parts = sep.split(output)
print "Killing %s with pid %s" % (procname,output_parts[1])
output = subprocess.Popen('kill -s 9 ' + output_parts[1], stdout=subprocess.PIPE, shell=True).communicate()[0]
print output
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment