get size of all installed packages

Meine /usr Partition war malwieder ganz schön voll. Da ich python-apt so lustig finde, gab es endlich wieder einen passenden Nagel für meinen Hammer. Das Ergebnis ist ein kleines Script, das alle Pakete sortiert nach Grösse ausgibt. Mit dpkg/apt/awk hab ich innerhalb von 20min nämlich nichts passendes gefunden.

#!/usr/bin/env python

import apt
import math

cache = apt.Cache()
list = []

def filesizeformat(bytes, precision=2):
    """Returns a humanized string for a given amount of bytes"""
    bytes = int(bytes)
    if bytes is 0:
        return '0bytes'
    log = math.floor(math.log(bytes, 1024))
    return "%.*f%s" % (
        precision,
        bytes / math.pow(1024, log),
        ['bytes', 'kb', 'mb', 'gb', 'tb','pb', 'eb', 'zb', 'yb'] [int(log)])

def pkgComp(a,b):
        if a.installedSize < b.installedSize:
                return -1
        elif a.installedSize == b.installedSize:
                return 0
        else:
                return 1

for pkg in cache:
        if pkg.isInstalled == True:
                list.append(pkg)

list.sort(pkgComp)
for item in list:
        print("%s %s") % (item.name,filesizeformat(item.installedSize))