#!/usr/bin/env python
import os, shutil

def clean_temporaries(dryrun=True, verbose=True, limit=None):
    exceptions = []
    for d in os.listdir('.'):
        if d[:len('urls-')] != 'urls-': continue
        subdirs = os.listdir(d)
        if limit is not None: subdirs = subdirs[:limit]
        for subdir in subdirs:
            if subdir == 'save': continue
            path = os.path.join(d, subdir)
            try:
                if os.path.isdir(path):
                    if verbose: print('rm -r %s' % path)
                    if not dryrun: shutil.rmtree(path)
                else:
                    if verbose: print('rm %s' % path)
                    if not dryrun: os.remove(path)
            except Exception as e:
                exceptions.append((path, e))
    if len(exceptions) > 0:
        print(exceptions)
        for path, e in exceptions:
            raise e

if __name__ == '__main__':
    clean_temporaries(dryrun=True, verbose=True, limit=20)
