What's using swap

If like me you're bored of looping over all /proc/<pid>/status files to find which application is actually using swap, here a tiny python script to ease the task.

The script outputs a list of processes using swap with the following format: <name> <uid> <swap usage>

Here's an example of what you can expect of the output of vmswap.py | sort -nk3:

pampd 501 4060kB
spampd 501 4100kB
spampd 501 4228kB
rsyslogd 0 4328kB
spampd 501 4368kB
spampd 501 7576kB
spampd 501 7612kB
httpd 48 10100kB
httpd 48 10140kB
httpd 48 10188kB
httpd 48 10216kB
httpd 48 10284kB
httpd 48 10308kB
httpd 48 10332kB
httpd 48 10388kB
httpd 48 10616kB
httpd 48 10628kB
httpd 48 10636kB
httpd 48 10848kB
httpd 48 10908kB
httpd 48 10916kB
httpd 48 10972kB
httpd 48 10980kB
httpd 48 11000kB
httpd 0 11084kB
httpd 48 11276kB
httpd 48 13056kB
httpd 48 14076kB
miniserv.pl 0 17412kB
memcached 496 23796kB
named 25 42388kB
mysqld 27 46292kB

And here's vmswap.py:

#!/bin/env python2
import os
import types
import subprocess

def get_command_output(cmd):
    # Get its output 
    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr=None, shell=False)
    output = process.communicate()
    return output[0].split('\n')

def main():
    # Defaults ps command and arguments
    ps_cmd = 'ps'
    ps_args = 'axcu'

    # Build ps command
    ps_cmd = '%s %s' % (ps_cmd, ps_args)

    # Get command output
    plist = get_command_output(ps_cmd)

    # Declare final list
    flist = []
    fadd  = flist.append
    proc = {}

    # Loop on output list
    for pline in plist:
        # Make a list out of each line
        proc_list = pline.split()
        if proc_list and os.path.isfile(os.path.join('/proc', proc_list[1], 'status')):
            proc[proc_list[1]] = {}
            for line in open(os.path.join('/proc', proc_list[1], 'status'), 'rb'):
                if 'Name:' in line:
                    pname = line.strip('\n')
                    pname = pname.split('\t')[1]
                    proc[proc_list[1]]['name'] = pname
                elif 'Uid:' in line:
                    puid = line.split('\t')[1]
                    proc[proc_list[1]]['uid'] = puid
                elif 'VmSwap:' in line:
                    pswap = line.strip('\n')
                    pswap = pswap.split('\t')[1]
                    proc[proc_list[1]]['swap'] = " ".join(pswap.split())

    for pid in proc:
        if 'swap' in proc[pid]:
            if proc[pid]['swap'] != '0 kB':
                output = '%s %s %s' % (proc[pid]['name'], proc[pid]['uid'], proc[pid]['swap'].replace(" ", ""))
                print(output)

if __name__ == '__main__':
    main()

Don't hesitate to contact me if you have any question or suggestion.