Advertisement
Guest User

Untitled

a guest
Feb 26th, 2023
637
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. import os
  2. import re
  3. import subprocess
  4. import argparse
  5.  
  6. # Additional argparse type
  7. def path(string):
  8. if not string:
  9. return ''
  10. s = os.path.expanduser(string)
  11. if not os.path.exists(s):
  12. raise argparse.ArgumentTypeError(f'No such file or directory: "{string}"')
  13. return s
  14.  
  15. archive_extensions = [
  16. '7z', 'zip', 'gz', 'gzip', 'tgz', 'bz2', 'bzip2', 'tbz2', 'tbz', 'tar', 'rar'
  17. ]
  18.  
  19. def list_archive_files(path):
  20. regex = '\.(' + '|'.join([re.escape(ext) for ext in archive_extensions]) + ')$'
  21. for f in os.listdir(path):
  22. if re.search(regex, f):
  23. yield os.path.join(path, f)
  24.  
  25. def is_archive_pwd_protected(path):
  26. try:
  27. cmds = [
  28. '7z',
  29. 't',
  30. '-pnone',
  31. path,
  32. ]
  33. subprocess.check_call(cmds, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  34. return False
  35. except:
  36. return True
  37.  
  38. def unpack_archives(path, output_path=None, password=None, delete_after=False):
  39. cmds = [
  40. '7z',
  41. 'x',
  42. '-aoa', # Overwrite existing
  43. '-o%s' % (output_path or os.path.dirname(path)),
  44. ]
  45. if password:
  46. cmds.append('-p%s' % password)
  47. cmds.append(None) # Placeholder for file
  48.  
  49. for file_path in list_archive_files(path):
  50. print('Extracting: %s' % file_path, end='')
  51. cmds[-1] = file_path
  52. try:
  53. if is_archive_pwd_protected(file_path):
  54. raise Exception()
  55. subprocess.check_call(cmds, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
  56. if delete_after:
  57. os.remove(file_path)
  58. except Exception:
  59. print(' - Skipped', end='')
  60. pass
  61. print()
  62.  
  63. def prompt_yes_no(query: str, default: bool = None) -> bool:
  64. s = '%s (%s/%s): ' % (query, 'Y' if default == True else 'y', 'N' if default == False else 'n')
  65. while True:
  66. inp = input(s).lower()
  67. if inp in ('yes', 'y'):
  68. return True
  69. elif inp in ('no', 'n'):
  70. return False
  71. elif default != None:
  72. return default
  73. if inp:
  74. print('Error: Please answer with "y" or "n"')
  75.  
  76. if __name__ == '__main__':
  77. parser = argparse.ArgumentParser()
  78. parser.add_argument('-i', '--input', default='.', type=path, help='Path to directory with archives')
  79. parser.add_argument('-d', '--delete', action='store_true', help='Delete archives after extraction')
  80. args = parser.parse_args()
  81.  
  82. unpack_archives(args.input, password='none', delete_after=args.delete)
  83. # delete_zips = prompt_yes_no('Delete zips', default=True)
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement