#!/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,
))