匿名用户
1级
2017-11-07 回答
前言
标准库是Python的一个组成部分。这些标准库是Python为你准备好的利器,可以让编程事半功倍。特别是有时候需要获取进程的pid,但又无法使用第三方库的时候。下面话不多说了,来一起看看详细的介绍吧。
方法适用linux平台.
方法1
使用subprocess 的check_output函数执行pidof命令
1234567
from subprocess import check_outputdef get_pid(name): return map(int,check_output(["pidof",name]).split()) In [21]: get_pid("chrome")Out[21]:[27698, 27678, 27665, 27649, 27540, 27530,]
方法2
使用pgrep命令,pgrep获取的结果与pidof获得的结果稍有不同.pgrep的进程id稍多几个.pgrep命令可以使适用subprocess的check_out函数执行
12345678910111213
import subprocess
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&