Cross-platform way to get PIDs by process name in python
Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using python or jython?
- I want something like
pidof
but in python. (I don't havepidof
anyway.) - I can't parse
/proc
because it might be unavailable (on HP-UX). - I do not want to run
os.popen('ps')
and parse the output because I think it is ugly (field sequence may be different in different OS). - Target platforms are Solaris, HP-UX, and maybe others.
Solution 1:
You can use psutil (https://github.com/giampaolo/psutil), which works on Windows and UNIX:
import psutil
PROCNAME = "python.exe"
for proc in psutil.process_iter():
if proc.name() == PROCNAME:
print(proc)
On my machine it prints:
<psutil.Process(pid=3881, name='python.exe') at 140192133873040>
EDIT 2017-04-27 - here's a more advanced utility function which checks the name against processes' name(), cmdline() and exe():
import os
import psutil
def find_procs_by_name(name):
"Return a list of processes matching 'name'."
assert name, name
ls = []
for p in psutil.process_iter():
name_, exe, cmdline = "", "", []
try:
name_ = p.name()
cmdline = p.cmdline()
exe = p.exe()
except (psutil.AccessDenied, psutil.ZombieProcess):
pass
except psutil.NoSuchProcess:
continue
if name == name_ or cmdline[0] == name or os.path.basename(exe) == name:
ls.append(p)
return ls
Solution 2:
There's no single cross-platform API, you'll have to check for OS. For posix based use /proc. For Windows use following code to get list of all pids with coresponding process names
from win32com.client import GetObject
WMI = GetObject('winmgmts:')
processes = WMI.InstancesOf('Win32_Process')
process_list = [(p.Properties_("ProcessID").Value, p.Properties_("Name").Value) for p in processes]
You can then easily filter out processes you need. For more info on available properties of Win32_Process check out Win32_Process Class