Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import re
- import subprocess
- import argparse
- # Additional argparse type
- def path(string):
- if not string:
- return ''
- s = os.path.expanduser(string)
- if not os.path.exists(s):
- raise argparse.ArgumentTypeError(f'No such file or directory: "{string}"')
- return s
- archive_extensions = [
- '7z', 'zip', 'gz', 'gzip', 'tgz', 'bz2', 'bzip2', 'tbz2', 'tbz', 'tar', 'rar'
- ]
- def list_archive_files(path):
- regex = '\.(' + '|'.join([re.escape(ext) for ext in archive_extensions]) + ')$'
- for f in os.listdir(path):
- if re.search(regex, f):
- yield os.path.join(path, f)
- def is_archive_pwd_protected(path):
- try:
- cmds = [
- '7z',
- 't',
- '-pnone',
- path,
- ]
- subprocess.check_call(cmds, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- return False
- except:
- return True
- def unpack_archives(path, output_path=None, password=None, delete_after=False):
- cmds = [
- '7z',
- 'x',
- '-aoa', # Overwrite existing
- '-o%s' % (output_path or os.path.dirname(path)),
- ]
- if password:
- cmds.append('-p%s' % password)
- cmds.append(None) # Placeholder for file
- for file_path in list_archive_files(path):
- print('Extracting: %s' % file_path, end='')
- cmds[-1] = file_path
- try:
- if is_archive_pwd_protected(file_path):
- raise Exception()
- subprocess.check_call(cmds, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- if delete_after:
- os.remove(file_path)
- except Exception:
- print(' - Skipped', end='')
- pass
- print()
- def prompt_yes_no(query: str, default: bool = None) -> bool:
- s = '%s (%s/%s): ' % (query, 'Y' if default == True else 'y', 'N' if default == False else 'n')
- while True:
- inp = input(s).lower()
- if inp in ('yes', 'y'):
- return True
- elif inp in ('no', 'n'):
- return False
- elif default != None:
- return default
- if inp:
- print('Error: Please answer with "y" or "n"')
- if __name__ == '__main__':
- parser = argparse.ArgumentParser()
- parser.add_argument('-i', '--input', default='.', type=path, help='Path to directory with archives')
- parser.add_argument('-d', '--delete', action='store_true', help='Delete archives after extraction')
- args = parser.parse_args()
- unpack_archives(args.input, password='none', delete_after=args.delete)
- # delete_zips = prompt_yes_no('Delete zips', default=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement