Skip to content

Instantly share code, notes, and snippets.

@chrplr
Created November 3, 2019 09:56
Show Gist options
  • Save chrplr/9728e5f1067b7301b9b5d9e89b6c987f to your computer and use it in GitHub Desktop.
Save chrplr/9728e5f1067b7301b9b5d9e89b6c987f to your computer and use it in GitHub Desktop.
pretty print the output of `du | sort -rn`
#! /usr/bin/env python3
# Time-stamp: <2019-11-03 10:53:53 christophe@pallier.org>
""" Cleanly format the output of ``du``.
Example:
du Documents/ | sort -rn | pretty_du | head
"""
import fileinput
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL) # prevents Broken pipe
def sizeof_fmt(num, suffix='B'):
"""
Converts a size in bytes into a human readable string.
Copied from https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
"""
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
for line in fileinput.input():
size, folder = line.split(sep='\t')
print(f'{sizeof_fmt(int(size) * 1024)}\t{size}\t{folder}', end='')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment