Advertisement
nuit

unrar.py

Mar 20th, 2011
408
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | None | 0 0
  1. #!/usr/bin/env python2
  2.  
  3. import subprocess as sp
  4. import os
  5. import re
  6. import time
  7. import tempfile
  8. import sys
  9.  
  10.  
  11. class unrar:
  12.     def __init__(self, rar, pwd):
  13.         self.rar = rar
  14.         self.pwd = pwd and "-p%s" % pwd or ""
  15.         #self.tmpdir = tempfile.mkdtemp()
  16.         self.tmpdir = "./tmp"
  17.    
  18.     def mkdir(self, file):
  19.         dir = os.path.dirname(file)
  20.         if dir and not os.path.isdir(dir):
  21.             os.makedirs(dir)
  22.  
  23.     def merge(self, fnin, fnout):
  24.         self.mkdir(fnout)
  25.         size = os.path.exists(fnout) and os.path.getsize(fnout)
  26.         with open(fnin) as fin:
  27.             with open(fnout, 'a') as fout:
  28.                 fin.seek(size)
  29.                 buf = fin.read(512*1024)
  30.                 tot = 0
  31.                 while buf:
  32.                     fout.write(buf)
  33.                     tot += len(buf)
  34.                     buf = fin.read(512*1024)
  35.  
  36.         print("Merged %d kB to %s (current size %d kB)" % (tot/1024, fnout, (size+tot)/1024))
  37.  
  38.     def list(self):
  39.         return sp.Popen(['nice', 'unrar', 'vb', self.pwd, self.rar], stdout=sp.PIPE).communicate()[0].splitlines()
  40.  
  41.     def extract(self, f):
  42.         fn = os.path.join(self.tmpdir, f)
  43.         while sp.Popen(['nice', 'unrar', 'x', '-kb', '-o+', self.pwd, self.rar, f, self.tmpdir], stderr=sp.PIPE, stdout=sp.PIPE).communicate()[1]:
  44.             self.merge(fn, f)
  45.             time.sleep(60)
  46.         self.merge(fn, f)
  47.         os.unlink(fn)
  48.    
  49.     def extract_all(self):
  50.         for f in self.list(): self.extract(f)
  51.  
  52. def main(params):
  53.     if len(params)<2:
  54.         print("usage: %s <archive> [<password>]" % params[0])
  55.         return 1
  56.    
  57.     archive = params[1]
  58.     try:
  59.         pwd = params[2]
  60.     except IndexError:
  61.         pwd = ""
  62.  
  63.     unrar(archive, pwd).extract_all()
  64.     return 0
  65.  
  66. if __name__ == "__main__":
  67.     sys.exit(main(sys.argv))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement