Auto-restart in (Python) and subprocess.Popen goodness

This is an auto-restart script for Orbited, but it can be modified to be used with other apps. This is presuming that there’s only one instance with that name running.

Basically, this script takes into account the fact that if you use ps -e| grep orbited, it’ll output a list of pids of which their process names are orbited. So in this case, every 60 seconds after orbited crashes, if there’s no process in the system process list named orbited, then this script will auto-start the process.

import os, time
from subprocess import *

lookfor = "orbited"

while True:
	pslist = Popen(["ps", "-e"], stdout=PIPE)
	orbited = Popen(["grep", lookfor], stdin=pslist.stdout, stdout = PIPE)

	output =  orbited.communicate()[0]

	if len(output) == 0:
		os.system("orbited")

	time.sleep(60)

A more useful tool from subprocess.Popen is if you use it as a process list and as a noob friendly task manager.

from subprocess import *
import os

print ""

lookfor = raw_input("Which Process should be terminated? [orbited] >> ")

if len(lookfor) <= 0:
	lookfor = "orbited"

#Give you a list of all processes
print "All System Processes With the name of "+lookfor
print ""

#Popen(["ps", "-e"])
os.system("ps -e| grep " + lookfor)

#Here's the command that we want to have
#ps -e| grep orbited
#It's a bit tricky to implement this in python

pslist = Popen(["ps", "-e"], stdout=PIPE)
orbited = Popen(["grep", lookfor], stdin=pslist.stdout, stdout = PIPE)

output =  orbited.communicate()[0]

output  = output.split("\n")

print "\nPIDs. Type 'y' to Kill this service"

for proc in output:
	proc = proc.split()
	if len(proc)>0:
		#proc = proc[0]
		print "\t" + proc[0] + "\tName: " + proc[3]
		if raw_input("\tDo you wish to Kill this Service? (y/N) ").lower() == "y":
	 		print "\tkilled " + proc[0]
			Popen(["kill", proc[0]])

print ""
This entry was posted in Programming, Python, Snippets and tagged , , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>