Skip to content

Instantly share code, notes, and snippets.

@ianchesal
Created September 1, 2012 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianchesal/3584919 to your computer and use it in GitHub Desktop.
Save ianchesal/3584919 to your computer and use it in GitHub Desktop.
Figures out the total size of all the sub-directories under a directory
#!/bin/env python
__doc__ = '''
dirsize.py
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: http://j.mp/MrXrzM')
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, p.stdout.read(), p.stderr.read())
class Unbuffered:
'''
An unbuffered output stream class suitable for replacing
stdout/stderr with.
'''
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, 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
self.jt.join()
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")
sys.stdout=Unbuffered(sys.stdout)
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)
thread_pool.append(t)
prev_thread = t
for t in thread_pool:
t.start()
# 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:
while(thread_pool[-1].isAlive()):
time.sleep(1)
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment