Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Figures out the total size of all the sub-directories under a directory
#!/bin/env python
__doc__ = '''
Figure out the size of everything contained in all the sub-directories under a target
in some sort of parallel manner. Try and produce some output that's not as terrible
to grok as du.
Useful if you're trying to figure out where you need to start pruning data sets on a
file system that's full.
import os, sys, threading, time, random, subprocess
from optparse import OptionParser
__version__ = '1.0'
def define_option_parser():
Create an option parser for this program.
parser = OptionParser(usage='usage: %prog [options] path1 [path2...]', version='%prog ' + __version__)
#parser.add_option('--pattern', dest='patterns', action='append', default=list(), help='Pattern to search file names for. Can be a glob pattern. Multiple --pattern options okay. No patterns means consider all files. For pattern help see:')
return parser
def docall(cmd):
Makes a subprocess call. Returns (retval, stdout, stderr).
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
retcode = p.wait()
return (retcode,,
class Unbuffered:
An unbuffered output stream class suitable for replacing
stdout/stderr with.
def __init__(self, stream): = stream
def write(self, data):
def __getattr__(self, attr):
return getattr(, attr)
class FindDirSize( threading.Thread ):
Class used to parallelize the data collection from the sub-directories.
def __init__ ( self, _dir, _jt):
self.dir = _dir
self.jt = _jt
threading.Thread.__init__ ( self )
def run(self):
st = random.randint(10,20)
(retcode, stdout, stderr) = docall(['du', '-hs', '%s' % self.dir])
if self.jt:
# Wait for thread before us to finish before we print our results
print '%s' % (stdout.strip())
def main():
parser = define_option_parser()
(options, args) = parser.parse_args()
if len(args) < 1:
parser.error("At least one path to search is required")
for path in args:
thread_pool = list()
prev_thread = None
for f in os.listdir(path):
full_f = os.path.join(path, f)
if os.path.isdir(full_f):
t = FindDirSize(full_f, prev_thread)
prev_thread = t
for t in thread_pool:
# We only have to wait for the last thread in the pool
# to finish since it blocks on all the others.
if len(thread_pool) > 0:
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment