free_disk.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import argparse
  2. import datetime
  3. import logging
  4. import os
  5. import shutil
  6. def main():
  7. argparser = argparse.ArgumentParser(
  8. description='Delete files with earliest modification date'
  9. ' until a minimum of --free-bytes are available on the respective disk')
  10. argparser.add_argument('-d', '--debug', action='store_true')
  11. argparser.add_argument('--free-bytes', type=int, required=True)
  12. argparser.add_argument('root_dir_path', metavar='ROOT_DIR')
  13. args = argparser.parse_args()
  14. logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO,
  15. format='%(asctime)s:%(levelname)s:%(message)s',
  16. datefmt='%Y-%m-%dT%H:%M:%S%z')
  17. disk_usage = shutil.disk_usage(args.root_dir_path)
  18. logging.debug(disk_usage)
  19. if disk_usage.free >= args.free_bytes:
  20. logging.debug('Requirement already fulfilled')
  21. return
  22. file_paths = [os.path.join(dirpath, filename)
  23. for dirpath, _, filenames in os.walk(args.root_dir_path)
  24. for filename in filenames]
  25. file_mtime_paths = [(os.stat(p).st_mtime, p) for p in file_paths]
  26. file_mtime_paths.sort()
  27. removed_files_counter = 0
  28. last_mtime = None
  29. for file_mtime, file_path in file_mtime_paths:
  30. if shutil.disk_usage(args.root_dir_path).free >= args.free_bytes:
  31. break
  32. os.remove(file_path)
  33. logging.debug('Removed file %s', file_path)
  34. removed_files_counter += 1
  35. last_mtime = file_mtime
  36. if removed_files_counter == 0:
  37. logging.warning('No files to remove')
  38. else:
  39. logging.info('Removed %d file(s) with modification date <= %s', removed_files_counter,
  40. datetime.datetime.utcfromtimestamp(last_mtime).isoformat('T'))
  41. if __name__ == '__main__':
  42. main()