Mini Shell
Direktori : /opt/sharedrads/ |
|
Current File : //opt/sharedrads/check_mem |
#!/opt/imh-python/bin/python3
"""Calculate and sort users by memory usage"""
import collections
import argparse
import subprocess
import tabulate
def parse_args():
"""Parse commandline arguments"""
parser = argparse.ArgumentParser(
description="""{}
RSS: Resident Set Size is memory actually in use by a process
VSZ: Virtual Set Size is a memory size assigned to a process during the
initial execution but not necessarily in use""".format(
__doc__
),
formatter_class=argparse.RawTextHelpFormatter,
)
parser.add_argument(
'-n', '--num', type=int, default=15, help='number of users to show'
)
parser.add_argument(
'-s',
'--sort',
choices=['vsz', 'rss', 'v', 'r'],
default='rss',
help='memory column to short by',
)
return parser.parse_args()
def main():
"""call parse_args, collect data from ps, sort, and print"""
args = parse_args()
cmd = ['ps', 'haxo', 'user,rss,vsz']
ps_out = subprocess.run(
cmd, text=True, stdout=subprocess.PIPE, check=False
).stdout
mem = collections.defaultdict(lambda: [0, 0])
for line in ps_out.splitlines():
user, rss, vsz = line.split()
mem[user][0] += int(rss)
mem[user][1] += int(vsz)
out = []
for user, datum in list(mem.items()):
out.append([user, datum[0], datum[1]])
if args.sort.startswith('r'):
out = sorted(out, key=lambda x: x[1])
else:
out = sorted(out, key=lambda x: x[2])
print(tabulate.tabulate(out[-args.num :], headers=['user', 'rss', 'vsz']))
if __name__ == '__main__':
main()
Zerion Mini Shell 1.0