anarchive - Inspired by this post by techb:
http://evilzone.org/scripting-languages/tarpy/msg58234/#msg58234. This is just a slight update from that thread adding fragile support for .rar files. But eventually I'd like to morph it into a tool that can do something like this:
$ anarchive -pattern "python" -o Python.Books.zip
Which would rip all files with "python" in the filename from every archive in the current directory, regardless of archive type, to a zip file (or whatever). I'm wondering, has this problem been solved before? I want something that will work the same across windows/linux/unix.
#!/usr/bin/env python
# ^ leverage env for a universal hashbang
# USAGE: ./unarchive file1 file2 file3 ...
import tarfile
import zipfile
import subprocess
import os
#XXX desperate for error checking
class Rarfile:
def __init__(self, fname):
self.fname = fname
def extractall(self, path):
wd = os.getcwd()
os.mkdir(path)
os.rename(fname, os.path.join(path, fname))
os.chdir(path)
subprocess.call(["unrar", "x", fname])
os.rename(fname, os.path.join(wd, fname))
os.chdir(wd)
def guesstype(fname):
return fname.split('.')[-1].lower()
def extract(fname, path="."):
archivetype = guesstype(fname)
if archivetype == "zip":
archive = zipfile.ZipFile(fname, 'r')
elif archivetype == "rar":
archive = Rarfile(fname)
else:
archive = tarfile.open(fname, "r:*")
archive.extractall(path)
if __name__ == "__main__":
import sys
files = sys.argv[1:]
for fname in files:
path = fname.split(".")[0]
print("Extracting %s" % (fname)) # Treat print as a function, env might
extract(fname, path) # find python3 instead of python2.