如何在Python中按进程名称获取PID?

时间:2022-03-09 16:45:07

Is there any way I can get the PID by process name in Python?

有什么方法可以通过Python中的进程名称获取PID吗?

  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 

For example I need to get 3110 by chrome.

例如,我需要通过chrome获得3110。

5 个解决方案

#1


40  

You can get the pid of processes by name using pidof through subprocess.check_output:

您可以使用pidof通过subprocess.check_output按名称获取进程的pid:

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]) will run the command as "pidof process_name", If the return code was non-zero it raises a CalledProcessError.

check_output([“pidof”,name])将命令作为“pidof process_name”运行,如果返回代码非零,则会引发CalledProcessError。

To handle multiple entries and cast to ints:

要处理多个条目并转换为整数:

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

In [21]: get_pid("chrome")

在[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]

Or pas the -s flag to get a single pid:

或者使用-s标志来获取单个pid:

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

In [25]: get_pid("chrome")
Out[25]: 27698

#2


5  

you can also use pgrep, in prgep you can also give pattern for match

你也可以使用pgrep,在prgep你也可以给匹配模式

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

you can also use awk with ps like this

你也可以像这样使用awk和ps

ps aux | awk '/name/{print $2}'

#3


4  

For posix (Linux, BSD, etc... only need /proc directory to be mounted) it's easier to work with os files in /proc. Its pure python, no need to call shell programs outside.

对于posix(Linux,BSD等...只需要安装/ proc目录),使用/ proc中的os文件更容易。它纯粹的python,无需在外面调用shell程序。

Works on python 2 and 3 ( The only difference (2to3) is the Exception tree, therefore the "except Exception", which i dislike but kept to maintain compatibility. Also could've created custom exception.)

适用于python 2和3(唯一的区别(2to3)是Exception树,因此是“Exception”,我不喜欢但保持兼容性。也可以创建自定义异常。)

#!/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)))

Sample Output (it works like pgrep):

示例输出(它像pgrep一样工作):

phoemur ~/python $ ./pgrep.py bash
1487         : -bash 
1779         : /bin/bash

#4


4  

To improve the Padraic's answer: when check_output returns a non-zero code, it raises a CalledProcessError. This happens when the process does not exists or is not running.

改进Padraic的答案:当check_output返回非零代码时,它会引发CalledProcessError。当进程不存在或未运行时会发生这种情况。

What I would do to catch this exception is:

我要做的就是抓住这个例外:

#!/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")

The output:

输出:

$ python pidproc.py
list of PIDS = 31840, 31841, 41942

#5


1  

Complete example based on the excellent @Hackaholic's answer:

基于优秀的@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()]

#1


40  

You can get the pid of processes by name using pidof through subprocess.check_output:

您可以使用pidof通过subprocess.check_output按名称获取进程的pid:

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]) will run the command as "pidof process_name", If the return code was non-zero it raises a CalledProcessError.

check_output([“pidof”,name])将命令作为“pidof process_name”运行,如果返回代码非零,则会引发CalledProcessError。

To handle multiple entries and cast to ints:

要处理多个条目并转换为整数:

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

In [21]: get_pid("chrome")

在[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]

Or pas the -s flag to get a single pid:

或者使用-s标志来获取单个pid:

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

In [25]: get_pid("chrome")
Out[25]: 27698

#2


5  

you can also use pgrep, in prgep you can also give pattern for match

你也可以使用pgrep,在prgep你也可以给匹配模式

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

you can also use awk with ps like this

你也可以像这样使用awk和ps

ps aux | awk '/name/{print $2}'

#3


4  

For posix (Linux, BSD, etc... only need /proc directory to be mounted) it's easier to work with os files in /proc. Its pure python, no need to call shell programs outside.

对于posix(Linux,BSD等...只需要安装/ proc目录),使用/ proc中的os文件更容易。它纯粹的python,无需在外面调用shell程序。

Works on python 2 and 3 ( The only difference (2to3) is the Exception tree, therefore the "except Exception", which i dislike but kept to maintain compatibility. Also could've created custom exception.)

适用于python 2和3(唯一的区别(2to3)是Exception树,因此是“Exception”,我不喜欢但保持兼容性。也可以创建自定义异常。)

#!/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)))

Sample Output (it works like pgrep):

示例输出(它像pgrep一样工作):

phoemur ~/python $ ./pgrep.py bash
1487         : -bash 
1779         : /bin/bash

#4


4  

To improve the Padraic's answer: when check_output returns a non-zero code, it raises a CalledProcessError. This happens when the process does not exists or is not running.

改进Padraic的答案:当check_output返回非零代码时,它会引发CalledProcessError。当进程不存在或未运行时会发生这种情况。

What I would do to catch this exception is:

我要做的就是抓住这个例外:

#!/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")

The output:

输出:

$ python pidproc.py
list of PIDS = 31840, 31841, 41942

#5


1  

Complete example based on the excellent @Hackaholic's answer:

基于优秀的@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()]