Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a process is running using Python on Linux [duplicate]

Tags:

python

linux

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.

like image 584
shash Avatar asked Oct 04 '11 11:10

shash


People also ask

How do I check if a python process is running in Linux?

wait() return output # This is the function you can use def isThisRunning( process_name ): output = findThisProcess( process_name ) if re.search('path/of/process'+process_name, output) is None: return False else: return True # Example of how to use if isThisRunning('some_process') == False: print("Not running") else: ...

How do you check if a particular process is running?

Bash commands to check running process: pgrep command – Looks through the currently running bash processes on Linux and lists the process IDs (PID) on screen. pidof command – Find the process ID of a running program on Linux or Unix-like system.

Which tools can you use to identify running processes in Linux?

You need to use the ps command. It provides information about the currently running processes, including their process identification numbers (PIDs). Both Linux and UNIX support the ps command to display information about all running process.


1 Answers

Try:

os.kill(pid, 0) 

Should succeed (and do nothing) if the process exists, or throw an exception (that you can catch) if the process doesn't exist.

like image 114
user9876 Avatar answered Sep 23 '22 05:09

user9876