Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a process is still running using Python on Linux? [duplicate]

The only nice way I've found is:

import sys import os  try:         os.kill(int(sys.argv[1]), 0)         print "Running" except:         print "Not running" 

(Source)
But is this reliable? Does it work with every process and every distribution?

like image 648
Andreas Thomas Avatar asked Sep 01 '08 15:09

Andreas Thomas


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 process is already running in Python?

Drop a pidfile somewhere (e.g. /tmp). Then you can check to see if the process is running by checking to see if the PID in the file exists. Don't forget to delete the file when you shut down cleanly, and check for it when you start up.

How do you check if a process is still running in Linux?

You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time.

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.


2 Answers

Mark's answer is the way to go, after all, that's why the /proc file system is there. For something a little more copy/pasteable:

 >>> import os.path  >>> os.path.exists("/proc/0")  False  >>> os.path.exists("/proc/12")  True 
like image 100
Aaron Maenpaa Avatar answered Sep 19 '22 00:09

Aaron Maenpaa


on linux, you can look in the directory /proc/$PID to get information about that process. In fact, if the directory exists, the process is running.

like image 41
Mark Harrison Avatar answered Sep 23 '22 00:09

Mark Harrison