一、使用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

Python 通过subprocess和commands获取进程PID

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐