I am trying to develop a Recursive Extractor. The problem is , it is Recursing Too Much (Evertime it found an archive type) and taking a performance hit.
So how can i improve below code?
My Idea 1:
Get the 'Dict' of direcories first , together with file types.Filetypes as Keys. Extract the file types. When an Archive is found Extract only that one. Then Regenerate Archive Dict again.
My Idea 2:
os.walk returns Generator. So is there something i can do with generators? I am new to Generators.
here is the current code :
import os, magic
m = magic.open( magic.MAGIC_NONE )
m.load()
archive_type = [ 'gzip compressed data',
'7-zip archive data',
'Zip archive data',
'bzip2 compressed data',
'tar archive',
'POSIX tar archive',
'POSIX tar archive (GNU)',
'RAR archive data',
'Microsoft Outlook email folder (>=2003)',
'Microsoft Outlook email folder']
def extractRecursive( path ,archives):
i=0
for dirpath, dirnames, filenames in os.walk( path ):
for f in filenames:
fp = os.path.join( dirpath, f )
i+=1
print i
file_type = m.file( fp ).split( "," )[0]
if file_type in archives:
arcExtract(fp,file_type,path,True)
extractRecursive(path,archives)
return "Done"
def arcExtract(file_path,file_type,extracted_path="/home/v3ss/Downloads/extracted",unlink=False):
import subprocess,shlex
if file_type in pst_types:
cmd = "readpst -o '%s' -S '%s'" % (extracted_path,file_path)
else:
cmd = "7z -y -r -o%s x '%s'" % (extracted_path,file_path)
print cmd
args= shlex.split(cmd)
print args
try:
sp = subprocess.Popen( args, shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE )
out, err = sp.communicate()
print out, err
ret = sp.returncode
except OSError:
print "Error no %s Message %s" % (OSError.errno,OSError.message)
pass
if ret == 0:
if unlink==True:
os.unlink(file_path)
return "OK!"
else:
return "Failed"
if __name__ == '__main__':
extractRecursive( 'Path/To/Archives' ,archive_type)