Created
February 20, 2017 09:03
-
-
Save marnitto/9664a1d9d4f577661d50e8e3e2a8f545 to your computer and use it in GitHub Desktop.
List processes, sort by memory usage, group by image name on Windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Tested on Windows 7~, Python 2.7 and 3.6. | |
# | |
# -*- coding: utf-8 -*- | |
import subprocess | |
import operator | |
res = subprocess.check_output(['tasklist']) | |
res = res.split(b'\r\n')[2:] | |
title = res[0].split() | |
image_width = len(title[0]) | |
mem_width = len(title[-1]) | |
stat = {} | |
for line in res[1:]: | |
imagename = line[:image_width].strip() | |
try: | |
mem = int(line[-mem_width:].replace(b',', b'').replace(b'K', b'') \ | |
.strip()) | |
except: | |
continue | |
if imagename not in stat: | |
stat[imagename] = 0 | |
stat[imagename] += mem | |
sorted_stat = sorted(stat.items(), key=operator.itemgetter(1))[::-1] | |
mem_width = max(len(str(sorted_stat[0][1])), 6) | |
print_fmt = '%-'+str(image_width)+'s %'+str(mem_width)+'s' | |
print(print_fmt % ('ImageName', 'Memory'.ljust(mem_width))) | |
print('='*image_width + ' ' + '='*mem_width) | |
for i, m in sorted_stat: | |
print(print_fmt % (i.decode('utf-8'), m)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output: