check if a process is running in python
- by shash
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.