Python 使用标准库根据进程名获取进程PID

时间:2023-03-09 17:57:33
Python 使用标准库根据进程名获取进程PID

应用场景

在进行 Linux 运维的环境中,我们经常会遇到维护同一台服务器上的多个程序,涉及到程序的启动、关闭和重启操作。

通常这些程序之间存在着相互依存的关系需要进行依次的启动关闭操作。

下面介绍几种通过进程名获取进程PID的方法:

方法一:

使用 subprocess 的 check_output 函数执行pidof命令

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

方法2:

使用 pgrep 命令,pgrep 获取的结果与 pidof 获得的结果稍有不同,pgrep 的进程 id 多几个。pgrep命令可以使用 subprocess 的 check_output 函数执行。

import subprocess
def get_process_id(name):
child = subprocess.Popen(['pgrep', '-f', name],stdout=subprocess.PIPE, shell=False)
response = child.communicate()[0]
return [int(pid) for pid in response.split()]

方法3:

直接读取/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)))

方法4:

获取当前脚本的进程pid

import os

os.getpid()