如何通过进程名称获取PID? [英] How to get PID by process name?

查看:416
本文介绍了如何通过进程名称获取PID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以在Python中按进程名称获取PID?

Is there any way I can get the PID by process name in 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 

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

For example I need to get 3110 by chrome.

推荐答案

您可以通过

check_output(["pidof",name])将以"pidof process_name"身份运行命令,如果返回码非零,则会引发CalledProcessError.

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

在[21]中:get_pid("chrome")

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

或者点击-s标志以获取单个pid:

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

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

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

这篇关于如何通过进程名称获取PID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆