Logo Search packages:      
Sourcecode: babiloo version File versions  Download package

compressed.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#    Copyright (C) 2008-2010 Ivan Garcia <contact@ivangarcia.org>
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import sys, os
import tarfile, zipfile, tempfile

class CompressedFile:
    def __init__(self, file_path):
        self.file_path = file_path
        self.compressed_file = None
        if tarfile.is_tarfile(file_path):
            self.compressed_file = tarfile.open(file_path)
            self.compressed_file_content = self.compressed_file
        elif zipfile.is_zipfile(file_path):
            self.compressed_file = zipfile.ZipFile(file_path)
            self.compressed_file_content = self.compressed_file.namelist()

        # compression type not supported
        else:
            return

        self.extracted_members = []

    def extract(self):
        extract_path = tempfile.gettempdir()
        print "extracting '%s' to:" % self.file_path, extract_path
        self.extracted_members = []
        for member in self.compressed_file_content:
            self.extract_member(member, extract_path=extract_path)
        return self.extracted_members

    def extract_member(self, member, extract_path):
        if isinstance(self.compressed_file, tarfile.TarFile):
            self.extracted_members.append(os.path.join(extract_path, member.name))
            self.compressed_file.extract(member, path=extract_path)
        elif isinstance(self.compressed_file, zipfile.ZipFile):
            fd, tempFilePath = tempfile.mkstemp()
            self.extracted_members.append(os.path.join(extract_path, tempFilePath))
            extract_member = os.path.join(extract_path, tempFilePath)
            if not os.path.isdir(os.path.dirname(extract_member)):
                print "mkdir:", os.path.dirname(extract_member)
                os.makedirs(os.path.dirname(extract_member))
            if not os.path.isdir(extract_member):
                outfile = open(extract_member, 'wb')
                outfile.write(self.compressed_file.read(member))
                outfile.close()

if __name__ == "__main__":
    cf = CompressedFile(sys.argv[1])
    print cf.extract()

Generated by  Doxygen 1.6.0   Back to index