Python 使用標準庫根據進程名獲取進程PID

應用場景python

在進行 Linux 運維的環境中,咱們常常會遇到維護同一臺服務器上的多個程序,涉及到程序的啓動、關閉和重啓操做。shell

一般這些程序之間存在着相互依存的關係須要進行依次的啓動關閉操做。服務器

 

下面介紹幾種經過進程名獲取進程PID的方法:運維

方法一:函數

使用 subprocess 的 check_output 函數執行pidof命令spa

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

方法2:code

使用 pgrep 命令,pgrep 獲取的結果與 pidof 得到的結果稍有不一樣,pgrep 的進程 id 多幾個。pgrep命令能夠使用 subprocess 的 check_output 函數執行。orm

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:blog

直接讀取/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()
相關文章
相關標籤/搜索