如何按进程名获取PID?

2024-04-29 19:02:16 发布

您现在位置: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 

例如,我需要通过chrome获取3110


Tags: 方法time进程resprcpuchromemem
3条回答

可以使用pidofsubprocess.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])将作为"pidof process_name"运行命令,如果返回代码为非零,则会引发调用的进程错误。

要处理多个条目并转换为int,请执行以下操作:

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

在[21]中:获取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]

或者通过-s标志获取单个pid:

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

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

对于posix(Linux、BSD等)。。。只需要挂载/proc目录)在/proc中使用操作系统文件更容易。 它的纯python,不需要在外部调用shell程序。

在Python2和3上工作(唯一的区别(2to 3)是异常树,因此是“except i on”,我不喜欢它,但为了保持兼容性。也可以创建自定义异常。)

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

示例输出(其工作方式类似于pgrep):

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

您还可以使用pgrep,在prgep中,您还可以提供匹配的模式

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

您还可以对这样的ps使用awk

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

相关问题 更多 >