Skip to content

Instantly share code, notes, and snippets.

@sharow
Last active August 29, 2015 14:04
Show Gist options
  • Save sharow/8ef261d034235320ca39 to your computer and use it in GitHub Desktop.
Save sharow/8ef261d034235320ca39 to your computer and use it in GitHub Desktop.
show swapped processes
#!/usr/bin/env python
# -*- Mode: python; tab-width: 4; indent-tabs-mode: nil; coding: utf-8; -*-
import sys
import subprocess
from operator import itemgetter
def show_swapped_processes():
p = subprocess.Popen('grep VmSwap /proc/*/status',
shell=True, stdout=subprocess.PIPE)
entries = []
for line in p.stdout.readlines():
s = str(line, encoding='utf8') if sys.version_info[0] == 3 else line
s = s.split(':')
pid = s[0].split('/')[2]
size_kb = int(s[2].split()[0])
if pid == 'self' or size_kb == 0:
continue
proc_name = None
try:
with open('/proc/{}/status'.format(pid)) as f:
for prop in f.readlines():
if prop.startswith('Name'):
proc_name = prop.split(':')[1].strip()
break
except:
continue
else:
entries.append((pid, proc_name, size_kb))
entries.sort(key=itemgetter(2), reverse=True)
print('{:^8}|{:^18}| {:^10} |'.format('pid', 'process name', 'size'))
for entry in entries:
print('{:<7} | {:>16} | {:>8} kb |'.format(*entry))
total = sum(map(itemgetter(2), entries))
print('*{:<28}{:>8} kb'.format('Total', total))
if __name__ == '__main__':
show_swapped_processes()
# EOF
''' output
$ ./swapped_process.py
pid | process name | size |
897 | python | 16916 kb |
898 | python | 13928 kb |
704 | systemd-journal | 4196 kb |
~~snip~~
235 | agetty | 100 kb |
*Total 68720 kb
$
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment