當前位置: 首頁>>代碼示例>>Python>>正文


Python pickle.UnpicklingError方法代碼示例

本文整理匯總了Python中pickle.UnpicklingError方法的典型用法代碼示例。如果您正苦於以下問題:Python pickle.UnpicklingError方法的具體用法?Python pickle.UnpicklingError怎麽用?Python pickle.UnpicklingError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pickle的用法示例。


在下文中一共展示了pickle.UnpicklingError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def __init__(self, getter=DEFAULT_GETTER, *args, **kwargs):
        super(TokenDictionaryFeature, self).__init__(getter=getter, *args, **kwargs)
        self._is_boolean = True
        
        if self._path is not None:
            try:
                self._value = pickle.load(open(self._path))
            except (pickle.UnpicklingError, ImportError, EOFError, IndexError, TypeError):
                self._value = compile_token(self._path, "utf-8")
            self._entries = None
        elif self._entries is not None:
            self._value = set()
            for entry in self._entries:
                entry = entry.strip()
                if entry:
                    self._value.add(entry)
        
        assert self._value is not None 
開發者ID:YoannDupont,項目名稱:SEM,代碼行數:20,代碼來源:dictionaryfeatures.py

示例2: Do_SConsignDir

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def Do_SConsignDir(name):
    try:
        fp = open(name, 'rb')
    except (IOError, OSError) as e:
        sys.stderr.write("sconsign: %s\n" % e)
        return
    try:
        sconsign = SCons.SConsign.Dir(fp)
    except KeyboardInterrupt:
        raise
    except pickle.UnpicklingError:
        err = "sconsign: ignoring invalid .sconsign file `%s'\n" % (name)
        sys.stderr.write(err)
        return
    except Exception as e:
        err = "sconsign: ignoring invalid .sconsign file `%s': %s\n" % (name, e)
        sys.stderr.write(err)
        return
    printentries(sconsign.entries, args[0])


############################################################################## 
開發者ID:Autodesk,項目名稱:arnold-usd,代碼行數:24,代碼來源:sconsign.py

示例3: fromFile

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def fromFile(cls, file):
        try:
            cacheName = file + ".pickle"
            cacheKey = binStat(file) + BOB_INPUT_HASH
            with open(cacheName, "rb") as f:
                persistedCacheKey = f.read(len(cacheKey))
                if cacheKey == persistedCacheKey:
                    return pickle.load(f)
        except (EOFError, OSError, pickle.UnpicklingError) as e:
            pass

        audit = cls()
        try:
            with gzip.open(file, 'rb') as gzf:
                audit.load(gzf, file)
            with open(cacheName, "wb") as f:
                f.write(cacheKey)
                pickle.dump(audit, f, -1)
        except OSError as e:
            raise ParseError("Error loading audit: " + str(e))
        return audit 
開發者ID:BobBuildTool,項目名稱:bob,代碼行數:23,代碼來源:audit.py

示例4: load

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def load(self):
        """Load the file from disk.

        Returns:
            bool: True if successfully loaded, False if the file
                doesn't exist.

        Raises:
            UnknownFormat: When the file exists but couldn't be loaded.
        """

        if not self._loaded and os.path.exists(self.file_path):
            with open(self.file_path, 'rb') as f:
                for loader in (pickle.load, json.load):
                    try:
                        f.seek(0)
                        self._store = loader(f)
                        self._loaded = True
                        break
                    except pickle.UnpicklingError:
                        pass
            # If the file exists and wasn't able to be loaded, raise an error.
            if not self._loaded:
                raise UnknownFormat('Failed to load file')
        return self._loaded 
開發者ID:afrase,項目名稱:kodiswift,代碼行數:27,代碼來源:storage.py

示例5: _get_authenticated_session

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def _get_authenticated_session(self, cookies_file):
        session = Session()
        try:
            cfile = open(cookies_file, 'rb')
        except FileNotFoundError:
            message = 'Could not open cookies file, either file does not exist or no read access.'
            raise InvalidCookies(message)
        try:
            session.cookies.update(pickle.load(cfile))
            self._logger.debug('Successfully loaded pickled cookie!')
            warnings.warn('Pickled cookie format is going to be deprecated in a future version, '
                          'please start using a text base cookie file!')
        except (pickle.UnpicklingError, KeyError, AttributeError, EOFError, ValueError):
            self._logger.debug('Trying to load text based cookies.')
            session = self._load_text_cookies(session, cfile)
        cfile.close()
        return session 
開發者ID:costastf,項目名稱:locationsharinglib,代碼行數:19,代碼來源:locationsharinglib.py

示例6: open_pickle

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def open_pickle(path: str):
    """Open a pickle and return loaded pickle object.
    :type path: str
    :param : path: File path to pickle file to be opened.
    :rtype : object
    """
    try:
        with open(path, 'rb') as opened_pickle:
            try:
                return pickle.load(opened_pickle)
            except Exception as pickle_error:
                logger.error(pickle_error)
                raise
    except FileNotFoundError as fnf_error:
        logger.error(fnf_error)
        raise
    except IOError as io_err:
        logger.error(io_err)
        raise
    except EOFError as eof_error:
        logger.error(eof_error)
        raise
    except pickle.UnpicklingError as unp_error:
        logger.error(unp_error)
        raise 
開發者ID:cltk,項目名稱:cltk,代碼行數:27,代碼來源:file_operations.py

示例7: do_trace

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def do_trace(proj, test_name, input_data, **kwargs):
    """
    trace, magic, crash_mode, crash_addr = load_cached_trace(proj, "test_blurble")
    """
    fname = os.path.join(bin_location, 'tests_data', 'runner_traces', '%s_%s_%s.p' % (test_name, os.path.basename(proj.filename), proj.arch.name))

    if os.path.isfile(fname):
        try:
            with open(fname, 'rb') as f:
                r = pickle.load(f)
                if type(r) is tuple and len(r) == 2 and r[1] == TRACE_VERSION:
                    return r[0]
        except (pickle.UnpicklingError, UnicodeDecodeError):
            print("Can't unpickle trace - rerunning")

    if tracer is None:
        raise Exception("Tracer is not installed and cached data is not present - cannot run test")

    runner = tracer.QEMURunner(project=proj, input=input_data, **kwargs)
    r = (runner.trace, runner.magic, runner.crash_mode, runner.crash_addr)
    with open(fname, 'wb') as f:
        pickle.dump((r, TRACE_VERSION), f, -1)
    return r 
開發者ID:angr,項目名稱:angr,代碼行數:25,代碼來源:common.py

示例8: __init__

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def __init__(self,
                 gtf_file,
                 fasta_file,
                 intron5prime_len=100,
                 intron3prime_len=100,
                 transform=None,
                 **kwargs):

        try:
            with open(gtf_file, 'rb') as f:
                self.exons = pickle.load(f)
        except (FileNotFoundError, pickle.UnpicklingError, ModuleNotFoundError):
            self.exons = generate_exons(gtf_file=gtf_file,
                                        overhang=(intron5prime_len,
                                                  intron3prime_len),
                                        **kwargs)
        import six
        if isinstance(fasta_file, six.string_types):
            fasta = Fasta(fasta_file, as_raw=False)
        self.fasta = fasta
        self.transform = transform 
開發者ID:kipoi,項目名稱:kipoiseq,代碼行數:23,代碼來源:splicing.py

示例9: unpickle_function

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def unpickle_function(mod_name, qname, self_):
    import importlib

    try:
        module = importlib.import_module(mod_name)
        qname = qname.split(".")
        func = module
        for q in qname:
            func = getattr(func, q)

        if self_ is not None:
            func = types.MethodType(func, self_)

        return func
    except (ImportError, AttributeError) as e:
        from pickle import UnpicklingError

        raise UnpicklingError from e 
開發者ID:Quansight-Labs,項目名稱:uarray,代碼行數:20,代碼來源:_backend.py

示例10: pickle_function

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def pickle_function(func):
    mod_name = getattr(func, "__module__", None)
    qname = getattr(func, "__qualname__", None)
    self_ = getattr(func, "__self__", None)

    try:
        test = unpickle_function(mod_name, qname, self_)
    except pickle.UnpicklingError:
        test = None

    if test is not func:
        raise pickle.PicklingError(
            "Can't pickle {}: it's not the same object as {}".format(func, test)
        )

    return unpickle_function, (mod_name, qname, self_) 
開發者ID:Quansight-Labs,項目名稱:uarray,代碼行數:18,代碼來源:_backend.py

示例11: test_badly_quoted_string

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def test_badly_quoted_string(self):
        # Issue #17710
        badpickles = [b"S'\n.",
                      b'S"\n.',
                      b'S\' \n.',
                      b'S" \n.',
                      b'S\'"\n.',
                      b'S"\'\n.',
                      b"S' ' \n.",
                      b'S" " \n.',
                      b"S ''\n.",
                      b'S ""\n.',
                      b'S \n.',
                      b'S\n.',
                      b'S.']
        for p in badpickles:
            self.check_unpickling_error(pickle.UnpicklingError, p) 
開發者ID:IronLanguages,項目名稱:ironpython3,代碼行數:19,代碼來源:pickletester.py

示例12: get_settings

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def get_settings(self):
        # Try opening and loading the settings from file.
        filename = os.path.join(self.__path, self.FILENAME)
        try:
            with open(filename, 'rb') as file:
                settings = pickle.load(file)
            # Test the pickle and check each setting inside it.
            assert isinstance(settings, dict)
            key_list = list(self.DEFAULT)
            for key in settings:
                assert isinstance(key, str)
                assert key in self.DEFAULT
                key_list.remove(key)
            # Add new settings as needed (when new ones are created).
            for key in key_list:
                settings[key] = self.DEFAULT[key]
            # Return old settings, or on error, the default settings.
            return False, settings
        except (IOError, pickle.UnpicklingError, AssertionError):
            return True, self.DEFAULT 
開發者ID:ActiveState,項目名稱:code,代碼行數:22,代碼來源:recipe-577638.py

示例13: unpickle_pipe

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def unpickle_pipe(self, fifo):
        frontend_utils.echo_info("Gathering data...")
        try:
            items = pickle.load(fifo)
            if items:
                if isinstance(items, Exception):
                    raise items
                return items
        except EOFError:
            return
        except pickle.UnpicklingError as e:
            frontend_utils.echo_error(f"Error retrieving data from process: {e}")
            raise
        except Exception as e:
            frontend_utils.echo_error(
                f"{type(e).__name__} occurred during analysis: {e}"
            )
            raise 
開發者ID:facebookincubator,項目名稱:memory-analyzer,代碼行數:20,代碼來源:analysis_utils.py

示例14: test_direct_rest_calls

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def test_direct_rest_calls(session, change_dir):
    """Ensure the direct_REST_calls.py example executes successfully."""
    from pickle import UnpicklingError

    # Mock up Session() to return the Betamax-recorded session
    def Session(*args, **kwargs):
        return session

    change_dir('examples')
    with open('direct_REST_calls.py') as f:
        # Remove import of Session to ensure mock function will be used
        # instead.
        code = f.read().replace('from sasctl import get, get_link, request_link, Session',
                                'from sasctl import get, get_link, request_link')
        try:
            six.exec_(code)
        except (UnpicklingError, KeyError) as e:
            if "'\xef'" in str(e):
                # Betamax recording adds additional bytes to the content which
                # breaks unpickling.  Ignore when this happens as correct
                # handling of binary contents should be validated in integration
                # tests
                pass 
開發者ID:sassoftware,項目名稱:python-sasctl,代碼行數:25,代碼來源:test_examples.py

示例15: test_get_file_content

# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import UnpicklingError [as 別名]
def test_get_file_content(self, dummy_file):

        with open(dummy_file, 'r') as f:
            target = f.read()

        # Should return binary pickle of text file contents
        content = files.get_file_content(self.filename)

        # Betamax recording seems to add 4 extra bytes to the beginning?
        # Doesn't occur during real requests.
        try:
            result = pickle.loads(content)
        except (KeyError, pickle.UnpicklingError):
            result = pickle.loads(content[4:])

        assert target == result 
開發者ID:sassoftware,項目名稱:python-sasctl,代碼行數:18,代碼來源:test_files.py


注:本文中的pickle.UnpicklingError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。