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


Python rarfile.RarFile方法代码示例

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


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

示例1: _download_and_extract

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def _download_and_extract(self, url, extract_to, ext='zip'):
        def _progress(count, block_size, total_size):
            if total_size > 0:
                print('\r>> Downloading %s %.1f%%' % (url,
                      float(count * block_size) / float(total_size) * 100.0), end=' ')
            else:
                print('\r>> Downloading %s' % (url), end=' ')
            sys.stdout.flush()
        urlretrieve = FancyURLopener().retrieve
        local_zip_path = os.path.join(self.data_dir, 'tmp.' + ext)
        urlretrieve(url, local_zip_path, _progress)
        sys.stdout.write("\n>> Finished downloading. Unzipping...\n")
        if ext == 'zip':
            with zipfile.ZipFile(local_zip_path, "r") as zip_ref:
                zip_ref.extractall(extract_to)
        else:
            with rarfile.RarFile(local_zip_path, "r") as zip_ref:
                zip_ref.extractall(extract_to)

        sys.stdout.write(">> Finished unzipping.\n")
        os.remove(local_zip_path)

        self.clear_statistics() 
开发者ID:simonmeister,项目名称:UnFlow,代码行数:25,代码来源:data.py

示例2: download_subtitle

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def download_subtitle(self, subtitle):

        # download as a zip
        logger.info('Downloading subtitle %r', subtitle.subtitle_id)
        r = self.session.get(subtitle.page_link, timeout=10)
        r.raise_for_status()

        if ".rar" in subtitle.page_link:
            logger.debug('Archive identified as rar')
            archive_stream = io.BytesIO(r.content)
            archive = RarFile(archive_stream)
            subtitle.content = self.get_subtitle_from_archive(subtitle, archive)
        elif ".zip" in subtitle.page_link:
            logger.debug('Archive identified as zip')
            archive_stream = io.BytesIO(r.content)
            archive = ZipFile(archive_stream)
            subtitle.content = self.get_subtitle_from_archive(subtitle, archive)
        else:
            subtitle.content = fix_line_ending(r.content) 
开发者ID:morpheus65535,项目名称:bazarr,代码行数:21,代码来源:supersubtitles.py

示例3: build_unpack_comic

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def build_unpack_comic(self, comic_path):
        logging.info("%s unpack requested" % comic_path)
        for root, dirs, files in os.walk(os.path.join(gazee.TEMP_DIR, "build"), topdown=False):
            for f in files:
                os.chmod(os.path.join(root, f), stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  # 0777
                os.remove(os.path.join(root, f))
        for root, dirs, files in os.walk(os.path.join(gazee.TEMP_DIR, "build"), topdown=False):
            for d in dirs:
                os.chmod(os.path.join(root, d), stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  # 0777
                os.rmdir(os.path.join(root, d))
        if comic_path.endswith(".cbr"):
            opened_rar = rarfile.RarFile(comic_path)
            opened_rar.extractall(os.path.join(gazee.TEMP_DIR, "build"))
        elif comic_path.endswith(".cbz"):
            opened_zip = zipfile.ZipFile(comic_path)
            opened_zip.extractall(os.path.join(gazee.TEMP_DIR, "build"))
        return 
开发者ID:hubbcaps,项目名称:gazee,代码行数:19,代码来源:comicscan.py

示例4: user_unpack_comic

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def user_unpack_comic(self, comic_path, user):
        logging.info("%s unpack requested" % comic_path)
        for root, dirs, files in os.walk(os.path.join(gazee.TEMP_DIR, user), topdown=False):
            for f in files:
                os.chmod(os.path.join(root, f), stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  # 0777
                os.remove(os.path.join(root, f))
        for root, dirs, files in os.walk(os.path.join(gazee.TEMP_DIR, user), topdown=False):
            for d in dirs:
                os.chmod(os.path.join(root, d), stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)  # 0777
                os.rmdir(os.path.join(root, d))
        if comic_path.endswith(".cbr"):
            opened_rar = rarfile.RarFile(comic_path)
            opened_rar.extractall(os.path.join(gazee.TEMP_DIR, user))
        elif comic_path.endswith(".cbz"):
            opened_zip = zipfile.ZipFile(comic_path)
            opened_zip.extractall(os.path.join(gazee.TEMP_DIR, user))
        return

    # This method will return a list of .jpg files in their numberical order to be fed into the reading view. 
开发者ID:hubbcaps,项目名称:gazee,代码行数:21,代码来源:comicscan.py

示例5: unrar

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def unrar(local_file):
    try:
        import rarfile
    except (ImportError, ModuleNotFoundError) as ex:
        raise ImportError('Cannot use unrar without rarfile: %s' % str(ex))

    path = os.path.dirname(os.path.abspath(local_file))
    print('\nunzipping in path: {}'.format(path))

    rar = rarfile.RarFile(local_file)
    dir = os.path.join(path, sorted(rar.namelist())[0])
    namelist = set([f.rstrip('/') for f in glob.glob("{}/**".format(dir), recursive=True)])
    rar_namelist = set([os.path.join(path, f) for f in rar.namelist()])

    if rar_namelist == namelist:
        dirs = set([f.rstrip('/') for f in glob.glob("{}/**/".format(dir), recursive=True)])
        files = list(namelist - dirs)
    else:
        files = []
        for filename in rar.namelist():
            if not is_file_in_dir(path, filename):
                rar.extract(filename, path)
            files.append(path + '/' + filename)
    print('done!')
    return files 
开发者ID:deep500,项目名称:deep500,代码行数:27,代码来源:download.py

示例6: unpack

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def unpack(self, file_path, temp_dir):
        # FIXME: need to figure out how to unpack multi-part files.
        try:
            with rarfile.RarFile(file_path) as rf:
                names = rf.namelist()
                encoding = self.detect_list_encoding(names)
                log.debug('Detected filename encoding: %s', encoding)

                for name in names:
                    try:
                        fh = rf.open(name)
                        self.extract_member(temp_dir, name, fh,
                                            encoding=encoding)
                    except Exception as ex:
                        # TODO: should this be a fatal error?
                        log.debug("Failed to unpack [%r]: %s", name, ex)
        except rarfile.NeedFirstVolume:
            raise ProcessingException('Cannot load splitted RAR files')
        except rarfile.Error as err:
            raise ProcessingException('Invalid RAR file: %s' % err) 
开发者ID:occrp-attic,项目名称:ingestors,代码行数:22,代码来源:rar.py

示例7: __decompress_rar

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def __decompress_rar(self):
        """extract a rar file."""
        try:
            rar_file = rarfile.RarFile(self.filepath)
            # check if there is a filename directory
            self.__check_filename_dir()

            os.mkdir(os.path.join(self.package_path, self.dir_name))

            rar_file.extractall(os.path.join(self.package_path, self.dir_name))
            rar_file.close()
        except (BadRarFile, NotRarFile):
            logger.error('File is not a rar file or is bad rar file')
            exit()

        return True 
开发者ID:WhaleShark-Team,项目名称:cobra,代码行数:18,代码来源:pickup.py

示例8: download_archive

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def download_archive(self, archive):
        """Download an archive's :attr:`~LegendasTVArchive.content`.

        :param archive: the archive to download :attr:`~LegendasTVArchive.content` of.
        :type archive: :class:`LegendasTVArchive`

        """
        logger.info('Downloading archive %s', archive.id)
        r = self.session.get(self.server_url + 'downloadarquivo/{}'.format(archive.id))
        raise_for_status(r)

        # open the archive
        archive_stream = io.BytesIO(r.content)
        if is_rarfile(archive_stream):
            logger.debug('Identified rar archive')
            archive.content = RarFile(archive_stream)
        elif is_zipfile(archive_stream):
            logger.debug('Identified zip archive')
            archive.content = ZipFile(archive_stream)
        else:
            raise ValueError('Not a valid archive') 
开发者ID:morpheus65535,项目名称:bazarr,代码行数:23,代码来源:legendastv.py

示例9: download_subtitle

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def download_subtitle(self, subtitle):
        if isinstance(subtitle, NekurSubtitle):
            # download the subtitle            
            r = self.session.get(subtitle.download_link, timeout=10)
            r.raise_for_status()

            # open the archive
            archive_stream = io.BytesIO(r.content)
            if is_rarfile(archive_stream):
                archive = RarFile(archive_stream)
            elif is_zipfile(archive_stream):
                archive = ZipFile(archive_stream)
            else:
                subtitle.content = r.content
                if subtitle.is_valid():
                    return
                subtitle.content = None

                raise ProviderError('Unidentified archive type')

            subtitle.content = self.get_subtitle_from_archive(subtitle, archive) 
开发者ID:morpheus65535,项目名称:bazarr,代码行数:23,代码来源:nekur.py

示例10: download_subtitle

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def download_subtitle(self, subtitle):
        r = self.session.get(subtitle.page_link, timeout=10)
        r.raise_for_status()

        # open the archive
        archive_stream = io.BytesIO(r.content)
        if is_rarfile(archive_stream):
            logger.debug('Archive identified as rar')
            archive = RarFile(archive_stream)
        elif is_zipfile(archive_stream):
            logger.debug('Archive identified as zip')
            archive = ZipFile(archive_stream)
        else:
            raise ProviderError('Unidentified archive type')

        subtitle.content = self.get_subtitle_from_archive(subtitle, archive) 
开发者ID:morpheus65535,项目名称:bazarr,代码行数:18,代码来源:hosszupuska.py

示例11: download_subtitle

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def download_subtitle(self, subtitle):
        if isinstance(subtitle, SubtitriIdSubtitle):
            # download the subtitle
            r = self.session.get(subtitle.download_link, timeout=10)
            r.raise_for_status()

            # open the archive
            archive_stream = io.BytesIO(r.content)
            if is_rarfile(archive_stream):
                archive = RarFile(archive_stream)
            elif is_zipfile(archive_stream):
                archive = ZipFile(archive_stream)
            else:
                subtitle.content = r.content
                if subtitle.is_valid():
                    return
                subtitle.content = None

                raise ProviderError('Unidentified archive type')

            subtitle.content = self.get_subtitle_from_archive(subtitle, archive) 
开发者ID:morpheus65535,项目名称:bazarr,代码行数:23,代码来源:subtitriid.py

示例12: read

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def read(self, fname, psw = None):
        """Return uncompressed data for archive entry.
        
        For longer files using :meth:`RarFile.open` may be better idea.

        Parameters:

            fname
                filename or RarInfo instance
            psw
                password to use for extracting.
        """

        f = self.open(fname, 'r', psw)
        try:
            return f.read()
        finally:
            f.close() 
开发者ID:entynetproject,项目名称:arissploit,代码行数:20,代码来源:rarfile.py

示例13: __init__

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def __init__(self, rarfile, mode="r", charset=None, info_callback=None,
                 crc_check=True, errors="stop"):
        """Open and parse a RAR archive.

        Parameters:

            rarfile
                archive file name
            mode
                only 'r' is supported.
            charset
                fallback charset to use, if filenames are not already Unicode-enabled.
            info_callback
                debug callback, gets to see all archive entries.
            crc_check
                set to False to disable CRC checks
            errors
                Either "stop" to quietly stop parsing on errors,
                or "strict" to raise errors.  Default is "stop".
        """
        self._rarfile = rarfile
        self._charset = charset or DEFAULT_CHARSET
        self._info_callback = info_callback
        self._crc_check = crc_check
        self._password = None
        self._file_parser = None

        if errors == "stop":
            self._strict = False
        elif errors == "strict":
            self._strict = True
        else:
            raise ValueError("Invalid value for 'errors' parameter.")

        if mode != "r":
            raise NotImplementedError("RarFile supports only mode=r")

        self._parse() 
开发者ID:BasioMeusPuga,项目名称:Lector,代码行数:40,代码来源:rarfile.py

示例14: open

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def open(self, fname, mode='r', psw=None):
        """Returns file-like object (:class:`RarExtFile`) from where the data can be read.

        The object implements :class:`io.RawIOBase` interface, so it can
        be further wrapped with :class:`io.BufferedReader`
        and :class:`io.TextIOWrapper`.

        On older Python where io module is not available, it implements
        only .read(), .seek(), .tell() and .close() methods.

        The object is seekable, although the seeking is fast only on
        uncompressed files, on compressed files the seeking is implemented
        by reading ahead and/or restarting the decompression.

        Parameters:

            fname
                file name or RarInfo instance.
            mode
                must be 'r'
            psw
                password to use for extracting.
        """

        if mode != 'r':
            raise NotImplementedError("RarFile.open() supports only mode=r")

        # entry lookup
        inf = self.getinfo(fname)
        if inf.isdir():
            raise TypeError("Directory does not have any data: " + inf.filename)

        # check password
        if inf.needs_password():
            psw = psw or self._password
            if psw is None:
                raise PasswordRequired("File %s requires password" % inf.filename)
        else:
            psw = None

        return self._file_parser.open(inf, psw) 
开发者ID:BasioMeusPuga,项目名称:Lector,代码行数:43,代码来源:rarfile.py

示例15: read

# 需要导入模块: import rarfile [as 别名]
# 或者: from rarfile import RarFile [as 别名]
def read(self, fname, psw=None):
        """Return uncompressed data for archive entry.

        For longer files using :meth:`RarFile.open` may be better idea.

        Parameters:

            fname
                filename or RarInfo instance
            psw
                password to use for extracting.
        """

        with self.open(fname, 'r', psw) as f:
            return f.read() 
开发者ID:BasioMeusPuga,项目名称:Lector,代码行数:17,代码来源:rarfile.py


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