Detecting if a program is currently running.

Brian ThisIsNotMyReal at ddress.com
Mon Dec 27 04:11:59 CET 2004


On a Slackware 9.1 box, I'm trying to detect if mpg123 is currently 
running/playing a song so that when the song is done, it'll play the next 
in the list.  The problem is that popen'ing ps doesn't always give a 
correct return.  My function is below and I added a second check that runs 
1 second later which sometimes works, sometimes doesn't.

Here's my function:

def pid_defunct():
        #1 = defunct processes
        #2 = show is currently playing
        #0 = no mpg123 processes found
        t = os.popen( "ps axc | grep '[mpg123] <defunct>'" ).read()
        if len(t) > 0:
                return 1
        else:
                t = os.popen( "ps axc | grep 'mpg123'" ).read()
                if len(t) > 0:
                        return 2
                else:
                        print "Check 1: mpg123 is dead"
                        #Check twice, because popen doesn't always return     
	    	    	    	   #correct value
                        time.sleep(1)
                        t = os.popen( "ps axc | grep 'mpg123'" ).read()
                        if len(t) > 0:
                                print "Check 1 was wrong"
                                return 2
                        else:
                                print "Check 2: mpg123 is dead"
                                return 0


This function is run during each iteration of a loop with a time.sleep(1) 
executed right before it.  Is there a better way to make this work?



More information about the Python-list mailing list