Skip to content

Instantly share code, notes, and snippets.

@trapexit
Created February 16, 2023 03:46
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 trapexit/14ef971951b6c1096a7acec203754faa to your computer and use it in GitHub Desktop.
Save trapexit/14ef971951b6c1096a7acec203754faa to your computer and use it in GitHub Desktop.
remove files from a path till storage is below a threshold
#!/usr/bin/env python
import os
import argparse
import stat
import psutil
def build_file_list(basepath):
file_list = []
for root, dirs, filenames in os.walk(basepath):
for filename in filenames:
try:
filepath = os.path.join(root,filename)
st = os.lstat(filepath)
entry = (st.st_mtime,filepath)
file_list.append(entry)
except:
pass
file_list.sort(reverse=True)
return file_list
def trim_path(basepath, target_percentage, verbose, execute):
current_percentage = psutil.disk_usage(basepath).percent
if verbose:
print(f'{basepath}: current% = {current_percentage}; target% = {target_percentage}')
if current_percentage < target_percentage:
return
file_list = build_file_list(basepath)
while ((current_percentage > target_percentage) and file_list):
filepath = file_list.pop()[1]
if verbose:
print(f'{filepath}',end='')
if execute:
try:
os.unlink(filepath)
if verbose:
print(': removed',end='')
except:
pass
if verbose:
print()
current_percentage = psutil.disk_usage(basepath).percent
if verbose:
print(f'{basepath}: current% = {current_percentage}; target% = {target_percentage}')
if __name__ == '__main__':
argparser = argparse.ArgumentParser(prog='pruner')
argparser.add_argument('--path',
required=True)
argparser.add_argument('--percentage',
type=float,
required=True)
argparser.add_argument('--verbose',
action='store_true',
required=False,
default=False)
argparser.add_argument('--execute',
action='store_true',
required=False,
default=False)
args = argparser.parse_args()
trim_path(args.path,
args.percentage,
args.verbose,
args.execute)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment