Skip to content

Instantly share code, notes, and snippets.

@marnitto
Created February 20, 2017 09:03
Show Gist options
  • Save marnitto/9664a1d9d4f577661d50e8e3e2a8f545 to your computer and use it in GitHub Desktop.
Save marnitto/9664a1d9d4f577661d50e8e3e2a8f545 to your computer and use it in GitHub Desktop.
List processes, sort by memory usage, group by image name on Windows
# 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))
@marnitto
Copy link
Author

Example output:

λ python taskmem.py              
ImageName                 Memory 
========================= =======
vmware-vmx.exe            1994628
slack.exe                 1909280
chrome.exe                1849452
Memory Compression        1164568
svchost.exe                469672
explorer.exe               272164
CefSharp.BrowserSubproces  189692
Everything.exe             174404
devenv.exe                 174260
primegrid_cllr.exe         166800
Mailbird.exe               128320

(snip)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment