how do I get the process list in Python?

Johan Carlsson picture Johan Carlsson · Jul 7, 2009 · Viewed 22.2k times · Source

How do I get a process list of all running processes from Python, on Unix, containing then name of the command/process and process id, so I can filter and kill processes.

Answer

Giampaolo Rodolà picture Giampaolo Rodolà · Mar 28, 2017

The right portable solution in Python is using psutil. You have different APIs to interact with PIDs:

>>> import psutil
>>> psutil.pids()
[1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, ..., 32498]
>>> psutil.pid_exists(32498)
True
>>> p = psutil.Process(32498)
>>> p.name()
'python'
>>> p.cmdline()
['python', 'script.py']
>>> p.terminate()
>>> p.wait()

...and if you want to "search and kill":

for p in psutil.process_iter():
    if 'nginx' in p.name() or 'nginx' in ' '.join(p.cmdline()):
        p.terminate()
        p.wait()