free_disk.py 1.4 KB

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