Python标准库获取进程PID的三种Linux实现方案

Chloe
Chloe
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍在Linux平台下,Python如何利用标准库获取指定进程名的PID。涵盖三种方法:通过subprocess调用pidof命令、使用pgrep命令(结果可能包含更多进程)以及直接读取/proc目录文件。文章提供完整代码示例,无需第三方库即可实现进程ID获取,适用于脚本监控与系统管理场景。

前言

标准库是Python语言的核心组成部分,提供了大量开箱即用的功能模块,能够显著提升开发效率。在某些特定场景下,例如受限环境中无法安装第三方库时,获取进程ID(PID)成为一个常见需求。本文将详细讲解几种基于Python标准库的实现方式,帮助读者快速掌握相关技巧。

本文所述方法仅适用于Linux操作系统平台。

方法一

利用subprocess模块中的check_output函数执行pidof命令。

from subprocess import check_output
def get_pid(name):
 return map(int,check_output(["pidof",name]).split())
 
In [21]: get_pid("chrome")
Out[21]:
[27698, 27678, 27665, 27649, 27540, 27530,]

方法二

使用pgrep命令。需要注意的是,pgrep返回的进程ID列表可能与pidof的结果存在差异,通常pgrep会返回更多的进程ID。该命令同样可以通过subprocess模块的check_output函数来执行。

import subprocess<br data-filtered="filtered">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()]

方法三

直接读取/proc目录下的相关文件。这种方法的优势在于无需启动外部shell进程,只需直接访问/proc目录下的文件即可获取进程信息,效率更高。

#!/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)))<br data-filtered="filtered"><br data-filtered="filtered">
phoemur ~/python $ ./pgrep.py bash
1487   : -bash 
1779   : /bin/bash

4. 获取当前脚本运行的进程ID

import os
 
os.getpid()

总结

以上就是本文的全部内容,希望这些方法能对您的学习或工作有所帮助。如果您有任何疑问或建议,欢迎在评论区留言交流,感谢大家对本站的支持。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表