check if a process is running in python

Posted by shash on Stack Overflow See other posts from Stack Overflow or by shash
Published on 2011-10-04T11:28:16Z Indexed on 2012/11/01 5:01 UTC
Read the original article Hit count: 108

Filed under:

I am trying to find if the process is running based on process id. The code is as follows based on one of the post on the forum. I cannot consider process name as there are more than one process running with the same name.

def findProcess( processId ):
    ps= subprocess.Popen("ps -ef | grep "+processId, shell=True, stdout=subprocess.PIPE)
    output = ps.stdout.read()
    ps.stdout.close()
    ps.wait()
    return output
def isProcessRunning( processId):
    output = findProcess( processId )
    if re.search(processId, output) is None:
        return true
    else:
        return False

Output :

1111 72312 72311   0   0:00.00 ttys000    0:00.00 /bin/sh -c ps -ef | grep 71676
1111 72314 72312   0   0:00.00 ttys000    0:00.00 grep 71676

It always return true as it can find the process id in the output string.

Any suggestions? Thanks for any help.

© Stack Overflow or respective owner

Related posts about python