當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。