What is the easiest way to see if a process with a given pid exists in Python?
posix, python
Solution
Instead of os.waitpid, you can also use os.kill with signal 0:
>>> os.kill(8861, 0)
>>> os.kill(12765, 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 3] No such process
>>>
Edit: more expansively:
import errno
import os
def pid_exists(pid):
try:
os.kill(pid, 0)
except OSError, e:
return e.errno == errno.EPERM
else:
return True
This works fine on my Linux box. I haven't verified that "signal 0" is actually Posix, but it's always worked on every Unix variant I've tried.
Problem
In a POSIX system, I want to see if a given process (PID 4356, for example) is running. It would be even better if I could get metadata about that process.