#!/usr/bin/python # =========================================================================== # # Script to average the size of all the subdirectories in a directory. # # Copyright (C) 2007 by Alex Brandt # # # # This program is free software; you can redistribute it and#or modify it # # under the terms of the GNU General Public License as published by the Free # # Software Foundation; version 2 of the License. # # # # This program is distributed in the hope that it will be useful, but WITHOUT # # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # # more details. # # # # You should have received a copy of the GNU General Public License along # # with this program; if not, write to the # # Free Software Foundation, Inc. # # 59 Temple Place - Suite 330 # # Boston, MA 02111-1307, USA # # =========================================================================== # import getopt import os import sys import datetime def usage(): print "usage: " + sys.argv[0] + " [-m ] [-d ] [-y ] [-D ] [-W ] [-v] " return 0 def help(): print "Usage: " + sys.argv[0] + " [options] " print "Deletes the files in the specified directory that are older than a specified" print "date. The default date if none is specified is yesterday." print print "Mandatory options for short options are mandatory for long options as well." print print "-m , --month Specifies the month to begin deleting files." print print "-d , --day Specifies the day of the month to begin deleting files." print print "-y , --year Specifies the year to begin deleting files." print print "-D , --days Specifies the number of days to save." print print "-W , --weeks Specifies the number of weeks to save." print print "-v , --verbose Make the output a bit more verbose, and include a progress bar." print print "-h , --help Prints out this help message." return 0 # ============================================================================ # # ProgressBar class grabbed from: # # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/168639 # # ============================================================================ # class ProgressBar: def __init__(self, minValue = 0, maxValue = 100, totalWidth = 80): self.progBar = "[]" # This holds the progress bar string. self.min = minValue self.max = maxValue self.span = maxValue - minValue self.width = totalWidth - 5 self.amount = 0 # When amount == max, we are 100% done self.UpdateAmount(0) # Build progress bar string def UpdateAmount(self, newAmount = 0): if newAmount < self.min: newAmount = self.min if newAmount > self.max: newAmount = self.max self.amount = newAmount # Figure out the new percent done, round to an integer. diffFromMin = float(self.amount - self.min) percentDone = int(round((diffFromMin/float(self.span)) * 100.0)) # Figure out how many hash bars the percentage should be. allFull = self.width - 2 numHashes = int(round((percentDone/100.0) * allFull)) # Build a progress bar with hashes and spaces. self.progBar = "[" + "#" * numHashes + " " * (allFull - numHashes) + "]" # Figure out where to put the percentage, roughly centered. percentString = str(percentDone) + "%" while len(percentString) != 4: percentString = " " + percentString # Slice the percentage into the bar. self.progBar = self.progBar + " " + percentString def __str__(self): return str(self.progBar) def main(): # Instantiate the variables for command line parsing. shortOptions = "m:d:y:D:W:vh" longOptions = ["month=", "day=", "year=", "days=", "weeks=", "verbose", "help"] _weeks = 0 _days = 1 _yesterday = datetime.date.today() + datetime.timedelta(days=-_days) + datetime.timedelta(weeks=-_weeks) _month = int(datetime.date.strftime(_yesterday, '%m')) _day = int(datetime.date.strftime(_yesterday, '%d')) _year = int(datetime.date.strftime(_yesterday, '%Y')) _date = False nItems = 0 nRemoved = 0 verbose = False try: optionList, arguments = getopt.gnu_getopt(sys.argv[1:], shortOptions, longOptions) except: usage() return 0 for option in optionList: if option[0] == "-m" or option[0] == "--month": _month = option[1] elif option[0] == "-d" or option[0] == "--day": _day = option[1] elif option[0] == "-y" or option[0] == "--year": _year = option[1] elif option[0] == "-D" or option[0] == "--days": _days = option[1] _date = datetime.datetime.today() - datetime.timedelta(days=int(_days)) elif option[0] == "-W" or option[0] == "--weeks": _weeks = option[1] _date = datetime.datetime.today() - datetime.timedelta(weeks=int(_weeks)) elif option[0] == "-v" or option[0] == "verbose": verbose = True elif option[0] == "-h" or option[0] == "--help": help() return 0 else: usage() return 1 if not _date: _date = datetime.datetime(_year, _month, _day) if len(arguments) != 1: print "No directory specified! Please, specify the directory to display." usage() return 1 directory = arguments[0] if not os.access(directory, os.F_OK): print "Could not enter " + directory + ". Do you have proper permissions to view the contents of this directory?" return 1 fileList = os.listdir(directory) if verbose: progress = ProgressBar(0, len(fileList), os.getenv("$COLUMNS", default=80)) print progress, for file in fileList: mtime = datetime.datetime.fromtimestamp(os.stat(directory + "/" + file)[9]) if _date > mtime: os.remove(directory + "/" + file) if verbose: nRemoved += 1 if verbose: nItems += 1 progress.UpdateAmount(nItems) print "\r" + str(progress), if verbose: print "Total Removals: " + str(nRemoved) + "/" + str(nItems) return 0 main()