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


Python tarfile.ExtractError方法代码示例

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


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

示例1: extract_tarfile

# 需要导入模块: import tarfile [as 别名]
# 或者: from tarfile import ExtractError [as 别名]
def extract_tarfile(tar_location, tar_flag, extract_location, name_of_file):
  """Attempts to extract a tar file (tgz).

  If the file is not found, or the extraction of the contents failed, the
  exception will be caught and the function will return False. If successful,
  the tar file will be removed.

  Args:
    tar_location: A string of the current location of the tgz file
    tar_flag: A string indicating the mode to open the tar file.
        tarfile.extractall will generate an error if a flag with permissions
        other than read is passed.
    extract_location: A string of the path the file will be extracted to.
    name_of_file: A string with the name of the file, for printing purposes.
  Returns:
    Boolean: Whether or not the tar extraction succeeded.
  """
  try:
    with tarfile.open(tar_location, tar_flag) as tar:
      tar.extractall(path=extract_location, members=tar)
    os.remove(tar_location)
    print "\t" + name_of_file + " successfully extracted."
    return True
  except tarfile.ExtractError:
    return False 
开发者ID:google,项目名称:fplutil,代码行数:27,代码来源:util.py

示例2: unpack_tarfile

# 需要导入模块: import tarfile [as 别名]
# 或者: from tarfile import ExtractError [as 别名]
def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
    """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`

    Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
    by ``tarfile.open()``).  See ``unpack_archive()`` for an explanation
    of the `progress_filter` argument.
    """
    try:
        tarobj = tarfile.open(filename)
    except tarfile.TarError:
        raise UnrecognizedFormat(
            "%s is not a compressed or uncompressed tar file" % (filename,)
        )
    try:
        tarobj.chown = lambda *args: None   # don't do any chowning!
        for member in tarobj:
            name = member.name
            # don't extract absolute paths or ones with .. in them
            if not name.startswith('/') and '..' not in name.split('/'):
                prelim_dst = os.path.join(extract_dir, *name.split('/'))

                # resolve any links and to extract the link targets as normal files
                while member is not None and (member.islnk() or member.issym()):
                    linkpath = member.linkname
                    if member.issym():
                        linkpath = posixpath.join(posixpath.dirname(member.name), linkpath)
                        linkpath = posixpath.normpath(linkpath)
                    member = tarobj._getmember(linkpath)

                if member is not None and (member.isfile() or member.isdir()):
                    final_dst = progress_filter(name, prelim_dst)
                    if final_dst:
                        if final_dst.endswith(os.sep):
                            final_dst = final_dst[:-1]
                        try:
                            tarobj._extract_member(member, final_dst)  # XXX Ugh
                        except tarfile.ExtractError:
                            pass    # chown/chmod/mkfifo/mknode/makedev failed
        return True
    finally:
        tarobj.close() 
开发者ID:MayOneUS,项目名称:pledgeservice,代码行数:43,代码来源:archive_util.py

示例3: unpack_tarfile

# 需要导入模块: import tarfile [as 别名]
# 或者: from tarfile import ExtractError [as 别名]
def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
    """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`

    Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
    by ``tarfile.open()``).  See ``unpack_archive()`` for an explanation
    of the `progress_filter` argument.
    """
    try:
        tarobj = tarfile.open(filename)
    except tarfile.TarError:
        raise UnrecognizedFormat(
            "%s is not a compressed or uncompressed tar file" % (filename,)
        )
    with contextlib.closing(tarobj):
        tarobj.chown = lambda *args: None   # don't do any chowning!
        for member in tarobj:
            name = member.name
            # don't extract absolute paths or ones with .. in them
            if not name.startswith('/') and '..' not in name.split('/'):
                prelim_dst = os.path.join(extract_dir, *name.split('/'))

                # resolve any links and to extract the link targets as normal files
                while member is not None and (member.islnk() or member.issym()):
                    linkpath = member.linkname
                    if member.issym():
                        linkpath = posixpath.join(posixpath.dirname(member.name), linkpath)
                        linkpath = posixpath.normpath(linkpath)
                    member = tarobj._getmember(linkpath)

                if member is not None and (member.isfile() or member.isdir()):
                    final_dst = progress_filter(name, prelim_dst)
                    if final_dst:
                        if final_dst.endswith(os.sep):
                            final_dst = final_dst[:-1]
                        try:
                            tarobj._extract_member(member, final_dst)  # XXX Ugh
                        except tarfile.ExtractError:
                            pass    # chown/chmod/mkfifo/mknode/makedev failed
        return True 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:41,代码来源:archive_util.py

示例4: extract_tar

# 需要导入模块: import tarfile [as 别名]
# 或者: from tarfile import ExtractError [as 别名]
def extract_tar(filename: str, destination_dir: str, mode="r"):
    """ Extracts tar, targz and other files

    Parameters
    ----------
    filename : str
        The tar zipped file
    destination_dir : str
        The destination directory in which the files should be placed
    mode : str
        A valid tar mode. You can refer to https://docs.python.org/3/library/tarfile.html
        for the different modes.

    Returns
    -------

    """
    msg_printer = Printer()
    try:
        with msg_printer.loading(f"Unzipping file {filename} to {destination_dir}"):
            stdout.flush()
            with tarfile.open(filename, mode) as t:
                t.extractall(destination_dir)

        msg_printer.good(f"Finished extraction {filename} to {destination_dir}")
    except tarfile.ExtractError:
        msg_printer.fail("Couldnot extract {filename} to {destination}") 
开发者ID:abhinavkashyap,项目名称:sciwing,代码行数:29,代码来源:common.py

示例5: extract_tar

# 需要导入模块: import tarfile [as 别名]
# 或者: from tarfile import ExtractError [as 别名]
def extract_tar(abs_path):
    """Extract a gzipped tar file from the given absolute_path

    :param str abs_path: The absolute path to the tar file
    :returns str untar_dir: The absolute path to untarred file
    """
    work_dir, tar_file = os.path.split(abs_path)
    os.chdir(work_dir)
    try:
        os.mkdir("remote")
    except OSError:
        LOG.error("Path exists already, not creating remote directory.")
    remote_path = os.path.abspath("remote")

    def safe_paths(tar_meta):
        """Makes sure all tar file paths are relative to the base path

        Orignal from https://stackoverflow.com/questions/
        10060069/safely-extract-zip-or-tar-using-python

        :param tarfile.TarFile tar_meta: TarFile object
        :returns tarfile:TarFile fh: TarFile object
        """
        for fh in tar_meta:
            each_f = os.path.abspath(os.path.join(work_dir, fh.name))
            if os.path.realpath(each_f).startswith(work_dir):
                yield fh
    try:
        with tarfile.open(tar_file, mode="r:gz") as tarf:
            tarf.extractall(path=remote_path, members=safe_paths(tarf))
    except tarfile.ExtractError as e:
        LOG.error("Unable to extract the file: %s", e)
        raise
    os.remove(abs_path)
    return remote_path 
开发者ID:openstack-archive,项目名称:syntribos,代码行数:37,代码来源:remotes.py

示例6: unpack_tarfile

# 需要导入模块: import tarfile [as 别名]
# 或者: from tarfile import ExtractError [as 别名]
def unpack_tarfile(filename, extract_dir, progress_filter=default_filter):
    """Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`

    Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined
    by ``tarfile.open()``).  See ``unpack_archive()`` for an explanation
    of the `progress_filter` argument.
    """
    try:
        tarobj = tarfile.open(filename)
    except tarfile.TarError:
        raise UnrecognizedFormat(
            "%s is not a compressed or uncompressed tar file" % (filename,)
        )
    with contextlib.closing(tarobj):
        # don't do any chowning!
        tarobj.chown = lambda *args: None
        for member in tarobj:
            name = member.name
            # don't extract absolute paths or ones with .. in them
            if not name.startswith('/') and '..' not in name.split('/'):
                prelim_dst = os.path.join(extract_dir, *name.split('/'))

                # resolve any links and to extract the link targets as normal
                # files
                while member is not None and (member.islnk() or member.issym()):
                    linkpath = member.linkname
                    if member.issym():
                        base = posixpath.dirname(member.name)
                        linkpath = posixpath.join(base, linkpath)
                        linkpath = posixpath.normpath(linkpath)
                    member = tarobj._getmember(linkpath)

                if member is not None and (member.isfile() or member.isdir()):
                    final_dst = progress_filter(name, prelim_dst)
                    if final_dst:
                        if final_dst.endswith(os.sep):
                            final_dst = final_dst[:-1]
                        try:
                            # XXX Ugh
                            tarobj._extract_member(member, final_dst)
                        except tarfile.ExtractError:
                            # chown/chmod/mkfifo/mknode/makedev failed
                            pass
        return True 
开发者ID:jpush,项目名称:jbox,代码行数:46,代码来源:archive_util.py

示例7: _extractall

# 需要导入模块: import tarfile [as 别名]
# 或者: from tarfile import ExtractError [as 别名]
def _extractall(self, path=".", members=None):
    """Extract all members from the archive to the current working
       directory and set owner, modification time and permissions on
       directories afterwards. `path' specifies a different directory
       to extract to. `members' is optional and must be a subset of the
       list returned by getmembers().
    """
    import copy
    import operator
    from tarfile import ExtractError
    directories = []

    if members is None:
        members = self

    for tarinfo in members:
        if tarinfo.isdir():
            # Extract directories with a safe mode.
            directories.append(tarinfo)
            tarinfo = copy.copy(tarinfo)
            tarinfo.mode = 448 # decimal for oct 0700
        self.extract(tarinfo, path)

    # Reverse sort directories.
    if sys.version_info < (2, 4):
        def sorter(dir1, dir2):
            return cmp(dir1.name, dir2.name)
        directories.sort(sorter)
        directories.reverse()
    else:
        directories.sort(key=operator.attrgetter('name'), reverse=True)

    # Set correct owner, mtime and filemode on directories.
    for tarinfo in directories:
        dirpath = os.path.join(path, tarinfo.name)
        try:
            self.chown(tarinfo, dirpath)
            self.utime(tarinfo, dirpath)
            self.chmod(tarinfo, dirpath)
        except ExtractError:
            e = sys.exc_info()[1]
            if self.errorlevel > 1:
                raise
            else:
                self._dbg(1, "tarfile: %s" % e) 
开发者ID:bunbun,项目名称:nested-dict,代码行数:47,代码来源:ez_setup.py

示例8: _extractall

# 需要导入模块: import tarfile [as 别名]
# 或者: from tarfile import ExtractError [as 别名]
def _extractall(self, path=".", members=None):
    """Extract all members from the archive to the current working
       directory and set owner, modification time and permissions on
       directories afterwards. `path' specifies a different directory
       to extract to. `members' is optional and must be a subset of the
       list returned by getmembers().
    """
    import copy
    import operator
    from tarfile import ExtractError
    directories = []

    if members is None:
        members = self

    for tarinfo in members:
        if tarinfo.isdir():
            # Extract directories with a safe mode.
            directories.append(tarinfo)
            tarinfo = copy.copy(tarinfo)
            tarinfo.mode = 448  # decimal for oct 0700
        self.extract(tarinfo, path)

    # Reverse sort directories.
    if sys.version_info < (2, 4):
        def sorter(dir1, dir2):
            return cmp(dir1.name, dir2.name)
        directories.sort(sorter)
        directories.reverse()
    else:
        directories.sort(key=operator.attrgetter('name'), reverse=True)

    # Set correct owner, mtime and filemode on directories.
    for tarinfo in directories:
        dirpath = os.path.join(path, tarinfo.name)
        try:
            self.chown(tarinfo, dirpath)
            self.utime(tarinfo, dirpath)
            self.chmod(tarinfo, dirpath)
        except ExtractError:
            e = sys.exc_info()[1]
            if self.errorlevel > 1:
                raise
            else:
                self._dbg(1, "tarfile: %s" % e) 
开发者ID:largelymfs,项目名称:topical_word_embeddings,代码行数:47,代码来源:ez_setup.py


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