当前位置: 首页>>代码示例>>Python>>正文


Python TarFile.gzopen方法代码示例

本文整理汇总了Python中tarfile.TarFile.gzopen方法的典型用法代码示例。如果您正苦于以下问题:Python TarFile.gzopen方法的具体用法?Python TarFile.gzopen怎么用?Python TarFile.gzopen使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tarfile.TarFile的用法示例。


在下文中一共展示了TarFile.gzopen方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_attrsFromFile

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
 def test_attrsFromFile(self):
     """
     Extracting a simple AppleDouble file representing some extended
     attributes should result in a dictionary of those attributes.
     """
     tarfile = TarFile.gzopen("sample.tgz", fileobj=StringIO(simpleTarWithXattrs))
     self.assertEqual(attrsFromFile(tarfile.extractfile("./._f")), {"alpha": "beta", "gamma": "delta"})
开发者ID:redtailtech,项目名称:calendarserver,代码行数:9,代码来源:test_appledouble.py

示例2: get_local_file_deps

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
    def get_local_file_deps(self, fname):
        from os import mkdir, system
        from os.path import exists
        from tarfile import TarFile
        from time import asctime, localtime

        if exists("/tmp/gtkpacman"):
            system("rm -rf /tmp/gtkpacman")

        mkdir("/tmp/gtkpacman", 0755)
        archive = TarFile.gzopen(fname)
        for member in archive.getmembers():
            archive.extract(member, "/tmp/gtkpacman")
            continue

        info_file = file("/tmp/gtkpacman/.PKGINFO")
        infos = info_file.read()
        info_file.close()

        infos_lines = infos.splitlines()
        deps = []
        conflicts = []

        for line in infos_lines:
            sides = line.split(" = ")
            if sides[0] == "depend":
                deps.append(sides[1])
            elif sides[0] == "conflict":
                conflicts.append(sides[1])
            continue

        system("rm -rf /tmp/gtkpacman")
        return deps, conflicts
开发者ID:BackupTheBerlios,项目名称:gtkpacman-svn,代码行数:35,代码来源:pacman.py

示例3: importData

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
 def importData(self, archive):
   if not archive:
     raise SwineException(self.tr("File name cannot be empty"))
   os.chdir(self.getPath())
   with TarFile.gzopen(archive, "r") as tar:
     tar.extractall(".")
   self.loadConfig()
开发者ID:dswd,项目名称:Swine,代码行数:9,代码来源:swinelib.py

示例4: getControl

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
def getControl(filename):
    from cStringIO import StringIO
    from tarfile import TarFile
    file = open(filename)
    if file.read(8) != "!<arch>\n":
        raise ValueError, "Invalid file"
    while True:
        name = file.read(16)
        date = file.read(12)
        uid = file.read(6)
        gid = file.read(6)
        mode = file.read(8)
        size = file.read(10)
        magic = file.read(2)
        if name == "control.tar.gz  ":
            data = file.read(int(size))
            sio = StringIO(data)
            tf = TarFile.gzopen("", fileobj=sio)
            try:
                control = tf.extractfile("./control")
            except KeyError:
                control = tf.extractfile("control")
            return control.read()
        else:
            file.seek(int(size), 1)
    return None
开发者ID:nikhilgv9,项目名称:winlibrepacman,代码行数:28,代码来源:loader.py

示例5: __init__

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
    def __init__(self, path):
        self.fd = TarFile.gzopen(path)
        self.pkg_info = defaultdict(list)
        self.members = None

        if self.parse_pkginfo():
            self.parse_contents()
开发者ID:godane,项目名称:archpwn,代码行数:9,代码来源:pkg.py

示例6: test_pack_plugin

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
def test_pack_plugin():
    data = pack_plugin(skeleton_path, 'skeleton')
    files = find_files(skeleton_path, 'skeleton')

    io = StringIO(data)
    tarfile = TarFile.gzopen(None,fileobj=io)

    tar_files = [info.name for info in tarfile]
    
    for norm, tar in zip(files, tar_files):
        tar = path.normpath(tar)
        assert norm == tar
开发者ID:fermat618,项目名称:pida,代码行数:14,代码来源:test_packer.py

示例7: test_propertiesFromTarball

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
    def test_propertiesFromTarball(self):
        """
        Extracting a tarball with included AppleDouble WebDAV property
        information should allow properties to be retrieved using
        L{PropertyStore}.
        """
        tf = TarFile.gzopen("sample.tgz", fileobj=StringIO(samplePropertyTar))
        tmpdir = self.mktemp()

        # Note that 'tarfile' doesn't know anything about xattrs, so while OS
        # X's 'tar' will restore these as actual xattrs, the 'tarfile' module
        # will drop "._" parallel files into the directory structure on all
        # platforms.
        tf.extractall(tmpdir)

        props = PropertyStore("bob", lambda: FilePath(tmpdir).child("f"))

        self.assertEqual(props[PropertyName.fromElement(HRef)], HRef("http://sample.example.com/"))
        self.assertEqual(props[PropertyName.fromElement(Depth)], Depth("1"))
        self.assertEqual(props[PropertyName.fromElement(GETContentType)], GETContentType("text/example"))
开发者ID:redtailtech,项目名称:calendarserver,代码行数:22,代码来源:test_appledouble.py

示例8: main

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
    def main(self, options, args):
	if options.quiet:
	    logging.getLogger().setLevel(logging.WARNING)

	if options.install_rdflib:
	    logging.info("downloading rdflib")
	    import os
	    from subprocess import Popen
	    from tarfile import TarFile
	    from urllib2 import urlopen, Request
	    from StringIO import StringIO

	    url = "http://rdflib.net/rdflib.tgz"
	    headers = {'User-agent': 'redfoot.py (%s)' % __version__}
	    f = urlopen(Request(url, None, headers))
	    sio = StringIO(f.read())
	    sio.seek(0)
	    tar = TarFile.gzopen("rdflib.tgz", fileobj=sio)

	    logging.info("extracting rdflib")
	    for member in tar:
		if member.name.endswith("setup.py"):
		    setup = member.name
		tar.extract(member)
	    dir, file = os.path.split(setup)
	    os.chdir(dir)

	    logging.info("installing rdflib")
	    p = Popen([sys.executable, "setup.py", "install"])
	    p.wait()
	    if "rdflib" in sys.modules:
		del sys.modules["rdflib"]
	    try:
		import rdflib
		logging.info("rdflib %s installed" % rdflib.__version__)
	    except ImportError, e:
		logging.info("rdflib not installed: %s" % e)    
	    sys.exit()
开发者ID:eikeon,项目名称:redfoot,代码行数:40,代码来源:redfoot-0.9.2.py

示例9: __init__

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
    def __init__(self, path):
        if path.endswith('.gz'):
            self.fd = TarFile.gzopen(path)
        elif path.endswith('.xz'):
            self.fd = TarFile.open(fileobj=LZMAFile(path))
        else:
            raise Exception('Unsupported file type %s' % path)

        self.pkg_info = defaultdict(list)
        self.members = []

        # Extract most used information

        if self.parse_pkginfo():
            self.parse_contents()

        self.name = self.pkg_info.get('pkgname')
        self.desc = self.pkg_info.get('pkgdesc')[0]
        self.depends = self.pkg_info.get('depend') or []
        self.groups = self.pkg_info.get('group') or []

        if isinstance(self.name, (list, tuple)) and len(self.name) == 1:
            self.name = self.name[0]
开发者ID:anas-alfar,项目名称:archpwn,代码行数:25,代码来源:pkg.py

示例10: Maildir

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
    # Find the mailbox in which to store the mail
    md = None
    if re.match('Inbox(\![0-9]+)?$', folder):
        md = Maildir(maildir)
    elif re.match('Inbox/', folder):
        # Nested folders under Inbox, put them under a folder named
        # 'INBOX'.
        folder = folder.replace('/', '.').replace('Inbox', 'INBOX')
        md = Maildir(path.join(maildir, '.' + folder), factory=None)
    elif re.match('Sent(\ Items.*)?', folder):
        md = Maildir(path.join(maildir, '.' + 'Sent'), factory=None)
    else:
        md = Maildir(path.join(maildir, '.' + folder), factory=None)
    # Store the mail
    md.add(msg)


if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("Usage: {} /path/to/zmmailbox.tgz /path/to/Maildir".format(sys.argv[0]))
        exit(1)
    with TarFile.gzopen(sys.argv[1]) as tf:
        print("Building metadata...")
        metadata = get_metadata(tf)
        maildir_path = sys.argv[2]
        # Create the top Maildir
        Maildir(maildir_path)
        for m in get_mails(tf):
            print("{}".format(m['name'][:20]))
            store_mail(tf, m, maildir_path, metadata)
开发者ID:YukthiSystems,项目名称:zimbra2maildir,代码行数:32,代码来源:zimbra2maildir.py

示例11: exportData

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
 def exportData(self, archive):
   if not archive:
     raise SwineException(self.tr("File name cannot be empty"))
   os.chdir(self.getPath())
   with TarFile.gzopen(archive, "w") as tar:
     tar.add(".") #recursive
开发者ID:dswd,项目名称:Swine,代码行数:8,代码来源:swinelib.py

示例12: range

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
from tarfile import TarFile
from zipfile import ZipFile

path = 'g:/geek/'

for i in range(0, 300)[::-1]:
    extract_path = path + str(i)
    #put_path =path +str(i + 1)
    file = open(extract_path, 'rb')
    strr = file.read()
    try:
        if "\x50\x4B\x03\x04" in strr:
            tar = ZipFile(extract_path)
            tar.extract(str(i - 1), path)
            tar.close()
            file.close()
        elif "\x1F\x8B\x08" in strr:
            tar = TarFile.gzopen(extract_path)
            tar.extract(str(i - 1), path)
            tar.close()
            file.close()
        elif "\x42\x5A\x68\x39" in strr:
            tar = TarFile.bz2open(extract_path)
            tar.extract(str(i - 1), path)
            tar.close()
            file.close()
        file.close()
    except:
        print "something error!"
开发者ID:zwhubuntu,项目名称:CTF-chal-code,代码行数:31,代码来源:geek_program_250_new.py

示例13: package

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
def package(target, source, env):
    """Builder action for packaging the distribution archives."""

    # Print out.
    print('')
    print("#######################")
    print("# Packaging the files #")
    print("#######################")

    # List of distribution files.
    type_list = [env['DIST_TYPE']]
    if type_list[0] == 'ALL':
        type_list = ['zip', 'tar']

    # Loop over the distribution files.
    for dist_type in type_list:
        # The file name.
        if dist_type == 'zip':
            file = env['DIST_FILE'] + '.zip'
        elif dist_type == 'tar':
            file = env['DIST_FILE'] + '.tar.bz2'
        elif dist_type == 'dmg':
            file = env['DIST_FILE'] + '.dmg'

        # Print out.
        print("\n\nCreating the package distribution " + repr(file) + ".\n")

        # Create the special Mac OS X DMG file and then stop execution.
        if dist_type == 'dmg':
            # Create the Mac OS X universal application.
            print("\n# Creating the Mac OS X universal application.\n\n")
            cmd = '%s setup.py py2app' % sys.executable
            print("%s\n" % cmd)
            pipe = Popen(cmd, shell=True, stdin=PIPE, close_fds=False)
            waitpid(pipe.pid, 0)

            # Create the dmg image.
            print("\n\n# Creating the DMG image.\n\n")
            cmd = 'hdiutil create -ov -fs HFS+ -volname "relax" -srcfolder dist/relax.app ../%s' % file
            print("%s\n" % cmd)
            pipe = Popen(cmd, shell=True, stdin=PIPE, close_fds=False)
            waitpid(pipe.pid, 0)

            # Stop executing.
            return

        # Open the Zip distribution file.
        if dist_type == 'zip':
            archive = ZipFile(path.pardir + path.sep + file, 'w', compression=8)

        # Open the Tar distribution file.
        elif dist_type == 'tar':
            if search('.bz2$', file):
                archive = TarFile.bz2open(path.pardir + path.sep + file, 'w')
            elif search('.gz$', file):
                archive = TarFile.gzopen(path.pardir + path.sep + file, 'w')
            else:
                archive = TarFile.open(path.pardir + path.sep + file, 'w')

        # Base directory.
        base = getcwd() + sep

        # Walk through the directories.
        for root, dirs, files in walk(getcwd()):
            # Skip the subversion directories.
            if search("\.svn", root):
                continue

            # Add the files in the current directory to the archive.
            for i in range(len(files)):
                # Skip any '.sconsign' files, hidden files, byte-compiled '*.pyc' files, or binary objects '.o', '.os', 'obj', 'lib', and 'exp'.
                if search("\.sconsign", files[i]) or search("^\.", files[i]) or search("\.pyc$", files[i]) or search("\.o$", files[i]) or search("\.os$", files[i]) or search("\.obj$", files[i]) or search("\.lib$", files[i]) or search("\.exp$", files[i]):
                    continue

                # Create the file name (without the base directory).
                name = path.join(root, files[i])
                name = name[len(base):]
                print('relax-' + version + path.sep + name)

                # The archive file name.
                arcname = 'relax-' + version + path.sep + name

                # Zip archives.
                if dist_type == 'zip':
                    archive.write(filename=name, arcname=arcname)

                # Tar archives.
                if dist_type == 'tar':
                    archive.add(name=name, arcname=arcname)

        # Close the archive.
        archive.close()

    # Final printout.
    print("\n\n\n")
开发者ID:belisario21,项目名称:relax_trunk,代码行数:97,代码来源:distrib.py

示例14: urlopen

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
        logging.getLogger().setLevel(logging.WARNING)

    if options.install_rdflib:
        logging.info("downloading rdflib")
        import os
        from subprocess import Popen
        from tarfile import TarFile
        from urllib2 import urlopen, Request
        from StringIO import StringIO

        url = "http://rdflib.net/rdflib.tgz"
        headers = {'User-agent': 'redfoot.py (%s)' % __version__}
        f = urlopen(Request(url, None, headers))
        sio = StringIO(f.read())
        sio.seek(0)
        tar = TarFile.gzopen("rdflib.tgz", fileobj=sio)

        logging.info("extracting rdflib")
        for member in tar:
            if member.name.endswith("setup.py"):
                setup = member.name
            tar.extract(member)
        dir, file = os.path.split(setup)
        os.chdir(dir)

        logging.info("installing rdflib")
        p = Popen([sys.executable, "setup.py", "install"])
        p.wait()
        if "rdflib" in sys.modules:
            del sys.modules["rdflib"]
        try:
开发者ID:eikeon,项目名称:redfoot,代码行数:33,代码来源:redfoot-0.9.1.py

示例15: file

# 需要导入模块: from tarfile import TarFile [as 别名]
# 或者: from tarfile.TarFile import gzopen [as 别名]
    description='Make a multi-file tex documents into a single tex file.')
  parser.add_argument(
    'master_tex', metavar='master', type=unicode,
    help='master .tex file to be converted.')
  parser.add_argument(
    'archive', metavar='archive', type=unicode,
    help='output archive file (tar.gz).')

  args = parser.parse_args()

  archive_base = re.sub(ur'\.tar\.gz$',u'',args.archive)
  archive_file = archive_base + '.tar.gz'

  master = args.master_tex

  with TarFile.gzopen(archive_file, 'w') as arv:
    LOGGER.info('Create archive "{}":'.format(archive_file))
    with NamedTemporaryFile(prefix='texarv_') as tempfile:
      with tempfile.file as tmp:
        recursive_print(master, tmp)
      arv.add(tempfile.name, arcname='ms.tex')
      LOGGER.info('  append manuscript file "ms.tex"')
      for items in FIGURE_PATH:
        for figpath,arcname in items.iteritems():
          arv.add(figpath, arcname=arcname)
          LOGGER.info(
            '  append figure file "{}" as "{}"'.format(figpath, arcname))
      for items in MISC_PATH:
        for miscpath,arcname in items.iteritems():
          if os.path.exists(miscpath):
            arv.add(miscpath, arcname=arcname)
开发者ID:xr0038,项目名称:letterize,代码行数:33,代码来源:texarchive.py


注:本文中的tarfile.TarFile.gzopen方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。