Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-platform way to get PIDs by process name in python

People also ask

How get PID process details?

In this quick article, we've explored how to get the name and the command line of a given PID in the Linux command line. The ps -p <PID> command is pretty straightforward to get the process information of a PID. Alternatively, we can also access the special /proc/PID directory to retrieve process information.

How find PID process name in Linux?

With Linux, the info is in the /proc filesystem. To get the command line for process id 9999, read the file /proc/9999/cmdline . And to get the process name for process id 9999, read the file /proc/9999/comm .


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

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


import psutil

process = filter(lambda p: p.name() == "YourProcess.exe", psutil.process_iter())
for i in process:
  print i.name,i.pid

Give all pids of "YourProcess.exe"


A note on ThorSummoner's comment

process = [proc for proc in psutil.process_iter() if proc.name == "YourProcess.exe"].

I have tried it on Debian with Python 3, I think it has to be proc.name() instead of proc.name.