Cómo obtener PID por nombre de proceso en Python?


¿Hay alguna forma de obtener el PID por nombre de proceso en Python?

  PID USER      PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+  COMMAND                                                                                        
 3110 meysam    20   0  971m 286m  63m S  14.0  7.9  14:24.50 chrome 

Por ejemplo, necesito obtener 3110 por chrome.

Author: Martin Thoma, 2014-11-01

5 answers

Puede obtener el pid de los procesos por nombre usando pidof a través del subproceso .check_output :

from subprocess import check_output
def get_pid(name):
    return check_output(["pidof",name])


In [5]: get_pid("java")
Out[5]: '23366\n'

check_output(["pidof",name]) ejecutará el comando como "pidof process_name", Si el código devuelto es distinto de cero, genera un CalledProcessError.

Para manejar múltiples entradas y lanzar a ints:

from subprocess import check_output
def get_pid(name):
    return map(int,check_output(["pidof",name]).split())

En [21]: get_pid("chrome")

Out[21]: 
[27698, 27678, 27665, 27649, 27540, 27530, 27517, 14884, 14719, 13849, 13708, 7713, 7310, 7291, 7217, 7208, 7204, 7189, 7180, 7175, 7166, 7151, 7138, 7127, 7117, 7114, 7107, 7095, 7091, 7087, 7083, 7073, 7065, 7056, 7048, 7028, 7011, 6997]

O pas la bandera -s para obtener un solo pid:

def get_pid(name):
    return int(check_output(["pidof","-s",name]))

In [25]: get_pid("chrome")
Out[25]: 27698
 43
Author: Padraic Cunningham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-26 11:46:17

También se puede utilizar pgrep, en prgep también se puede dar el patrón para el partido

import subprocess
child = subprocess.Popen(['pgrep','program_name'], stdout=subprocess.PIPE, shell=True)
result = child.communicate()[0]

También puedes usar awk con ps como este

ps aux | awk '/name/{print $2}'
 5
Author: Hackaholic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-01 04:40:46

Para posix (Linux, BSD, etc... solo necesita el directorio /proc para ser montado) es más fácil trabajar con archivos de sistema operativo en /proc. Es python puro, sin necesidad de llamar a programas de shell fuera.

Funciona en python 2 y 3 ( La única diferencia (2to3) es el árbol de excepciones, por lo tanto el " excepto Excepción", que no me gusta, pero se mantuvo para mantener la compatibilidad. También podría haber creado excepción personalizada.)

#!/usr/bin/env python

import os
import sys


for dirname in os.listdir('/proc'):
    if dirname == 'curproc':
        continue

    try:
        with open('/proc/{}/cmdline'.format(dirname), mode='rb') as fd:
            content = fd.read().decode().split('\x00')
    except Exception:
        continue

    for i in sys.argv[1:]:
        if i in content[0]:
            print('{0:<12} : {1}'.format(dirname, ' '.join(content)))

Salida de muestra (funciona como pgrep):

phoemur ~/python $ ./pgrep.py bash
1487         : -bash 
1779         : /bin/bash
 4
Author: Fernando,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-13 20:30:05

Para mejorar la respuesta del Padraic: cuando check_output devuelve un código distinto de cero, genera un CalledProcessError. Esto sucede cuando el proceso no existe o no se está ejecutando.

Lo que haría para atrapar esta excepción es:

#!/usr/bin/python

from subprocess import check_output, CalledProcessError

def getPIDs(process):
    try:
        pidlist = map(int, check_output(["pidof", process]).split())
    except  CalledProcessError:
        pidlist = []
    print 'list of PIDs = ' + ', '.join(str(e) for e in pidlist)

if __name__ == '__main__':
    getPIDs("chrome")

La salida:

$ python pidproc.py
list of PIDS = 31840, 31841, 41942
 4
Author: Alejandro Blasco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-11 11:00:10

Ejemplo completo basado en la excelente respuesta de @Hackaholic :

def get_process_id(name):
    """Return process ids found by (partial) name or regex.

    >>> get_process_id('kthreadd')
    [2]
    >>> get_process_id('watchdog')
    [10, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61]  # ymmv
    >>> get_process_id('non-existent process')
    []
    """
    child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
    response = child.communicate()[0]
    return [int(pid) for pid in response.split()]
 3
Author: Dennis Golomazov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-23 02:36:00