views:

4245

answers:

4

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?

+10  A: 

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.

Mark Harrison
+3  A: 

It should work on any POSIX system (although looking at the /proc filesystem, as others have suggested, is easier if you know it's going to be there).

However: os.kill may also fail if you don't have permission to signal the process. You would need to do something like:

import sys
import os
import errno

try:
    os.kill(int(sys.argv[1]), 0)
except OSError, err:
    if err.errno == errno.ESRCH:
        print "Not running"
    elif err.errno == errno.EPERM:
        print "No permission to signal this process!"
    else:
        print "Unknown error"
else:
    print "Running"
dF
+6  A: 

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
Aaron Maenpaa
+3  A: 

// But is this reliable? Does it work with every process and every distribution?

Yes, it should work on any Linux distribution. Be aware that /proc is not easily available on Unix based systems, though (FreeBSD, OSX).

Marius Ursache