python 从linux中的/ proc中提取进程统计信息

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 从linux中的/ proc中提取进程统计信息相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: cody kochmann
# @Date:   2017-03-21 11:16:34
# @Last Modified time: 2017-03-21 11:30:16

'''extracts the process statistics from /proc in linux'''

__all__ = 'proc_info', 'vm_info'

from os import getpid
from os.path import isfile

# yields the lines of a file
readlines=lambda i:(l.replace('\n','') for l in open(i).readlines()) if isfile(i) else ''

# yields the lines of the current process proc file
proc_lines=lambda:readlines('/proc/{}/status'.format(getpid()))

# converts tabs to spaces
rm_tabs=lambda s:s.replace('\t','  ')

# removes useless spaces in a string
strip = lambda s:(s.strip() if not '  ' in rm_tabs(s) else strip(rm_tabs(s).replace('  ',' ')))

# takes a "key:value" string and returns it as a dict { "key": "value" }
make_kv=lambda l:{l[0]:l[1]} if len(l)==2 else make_kv(tuple(strip(i) for i in l.split(':')))

# dict key generator
keys=lambda d:(i for i in d.keys())

# dict val generator
vals=lambda d:(i for i in d.values())

# joins an iterable collection of dictionaries and merges them into one
join_kv=lambda it:{next(keys(d)):next(vals(d)) for d in it}

# returns a dict with all of the process proc values extracted
proc_info=lambda:join_kv(make_kv(l) for l in proc_lines())

# returns the process 'Vm' info from the proc file
vm_info=lambda p=proc_info(): {k:p[k] for k in p if k.startswith('Vm')}

if __name__ == '__main__':
  # load the proc info
  p = proc_info()
  p = vm_info()

  # stop if the proc info is empty
  if not len(p):
    exit('couldnt find the /proc file')

  # variables for formatting
  longest_key = max(len(k) for k in p)
  longest_val = max(len(str(p[k]).split(' ')[0]) for k in p)
  col_margin = 2

  # print the output
  for k in p:
    print('{0:{lk}}{1:{lv}}{2}'.format(
      k, p[k].split(' ')[0], p[k].split(' ')[1],
      lk=longest_key+col_margin,
      lv=longest_val+col_margin,
    ))

以上是关于python 从linux中的/ proc中提取进程统计信息的主要内容,如果未能解决你的问题,请参考以下文章

从 Linux 中的 /proc 文件系统获取硬件信息

将一个文件中的内容读出来并写入数据库表中,用proc语言

linux 使用 /proc 文件系统

使用python进行服务器监控

哪个函数可以替换Linux内核2.6.32中的“create_proc_info_entry”?

Linux环境下文本处理,提取需要的内容?