python 使用标准库根据进程名获取进程的pid

有时候需要获取进程的pid,但又无法使用第三方库的时候.

方法适用linux平台.

方法1

使用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,]

 

方法2

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

import subprocess
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()]

方法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)))

phoemur ~/python $ ./pgrep.py bash 1487 : -bash 1779 : /bin/bash

  

4,获取当前脚本的pid进程

import os

os.getpid()

  

  

转载于:https://www.cnblogs.com/cppddz/p/7758094.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值