Josh Gibson
Josh Gibson

Reputation: 22968

What is the easiest way to see if a process with a given pid exists in Python?

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.

Upvotes: 7

Views: 2659

Answers (6)

Giampaolo Rodolà
Giampaolo Rodolà

Reputation: 13076

In a portable way, by using psutil ( https://github.com/giampaolo/psutil )

>>> import psutil, os
>>> psutil.pid_exists(342342)
False
>>> psutil.pid_exists(os.getpid())
True
>>> 

Upvotes: 3

user25148
user25148

Reputation:

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.

Upvotes: 11

phihag
phihag

Reputation: 288298

Look at /proc/pid. This exists only of the process is running, and contains lots of information.

Upvotes: 1

SpliFF
SpliFF

Reputation: 39014

On linux at least the /proc directory has what you are looking for. It's basically system data from the kernel represented as directories and files. All the numeric directories are details of processes. Just use the basic python os functions to get at this data:

#ls /proc
1      17    18675  25346  26390  28071  28674  28848  28871  29347  590   851   874  906   9621  9655       devices      iomem     modules ...

#ls /proc/1
auxv  cmdline  cwd  environ  exe  fd  maps  mem  mounts  root  stat  statm  status  task  wchan

#cat /proc/1/cmdline
init [3]

Upvotes: 4

Jamie Love
Jamie Love

Reputation: 5636

One way to do this to get information would be:

import commands
output = commands.getstatusoutput("ps -ef | awk '{print $2}' | grep MYPID")

See: http://docs.python.org/library/commands.html

I think:

commands.getoutput(...) 

could be used to get metadata available on the 'ps' line. Since you're using a POSIX system, I imagine ps (or equivalent) would be available (e.g. prstat under Solaris).

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 320039

os.waitpid() might be of help:

try:
    os.waitpid(pid, 0)
except OSError:
    running = False
else:
    running = True

Upvotes: 0

Related Questions