Python 获取进程PID

Python 获取进程PID   python subprocess pid   python commands pid   Shell/Python  
一、使用subprocess模块通过查找关键字获取进程PID
#!/usr/bin/python
import subprocess
import sys
import logging
import os

gameproc = ["loginserver","gameserver","dbserver","logserver"]

def getPid(process):
    cmd = "ps aux| grep '%s'|grep -v grep " % process
    logging.info(cmd)
    out = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
    infos = out.stdout.read().splitlines()
    pidlist = []
    if len(infos) >= 1:
        for i in infos:
            pid = i.split()[1]
            if pid not in pidlist:
                pidlist.append(pid)
        return pidlist
    else:
        return -1

for process in gameproc:
                pid = getPid(process)
二、Python commands获取进程id
  • 如果有同名进程,这样只能取到第一个进程的ID
#!/usr/bin/python
import commands
import sys

def getPid(process):
    cmd = "ps aux | grep '%s' " % process
    logging.info(cmd)
    info = commands.getoutput(cmd)
    infos = info.split()
    if len(infos) > 1:
        return infos[1]
    else:
        return -1