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


Question

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?

1
35
5/9/2016 6:11:10 AM

Accepted Answer

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
51
9/1/2008 6:06:42 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon