你可以通过名字使用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])将运行命令“pidof process_name”,如果返回代码不为零,则会引发CalledProcessError.

处理多个entris并转换为ints:

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

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

或者pas -s标志来获取一个pid:

def get_pid(name):
return int(check_output(["pidof","-s",name]))
In [25]: get_pid("chrome")
Out[25]: 27698