#!/usr/bin/env python3
# swapusage -- show current swap usage for all running processes
#
# A port of shell-based `swapusage` tool by Erik Ljungstrom, Mikko
# Rantalainen, and Marc Methot.
import argparse
import glob
import os

parser = argparse.ArgumentParser()
args = parser.parse_args()

usage = []
for dir in glob.glob("/proc/[0-9]*/"):
    pid = os.path.basename(dir.rstrip("/"))
    with open("%s/comm" % dir, "r") as fh:
        name = fh.read().strip()
    swap = 0
    with open("%s/status" % dir, "r") as fh:
        for line in fh:
            if line.startswith("VmSwap"):
                swap += int(line.split()[1])
    if swap > 0:
        usage += [(swap, name, pid)]
usage.sort()

fmt = "%9s kB  %s"
total = 0
for swap, name, pid in usage:
    print(fmt % (swap, "%s (%s)" % (name, pid)))
    total += swap
print(fmt % (total, "TOTAL"))
