本文整理匯總了Python中pickle.PicklingError方法的典型用法代碼示例。如果您正苦於以下問題:Python pickle.PicklingError方法的具體用法?Python pickle.PicklingError怎麽用?Python pickle.PicklingError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pickle
的用法示例。
在下文中一共展示了pickle.PicklingError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __getstate__
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def __getstate__(self):
d = dict(self.__dict__)
def get_pickleable_dict(cacheDict):
pickleableCache = dict()
for k, v in cacheDict.items():
try:
_pickle.dumps(v)
pickleableCache[k] = v
except TypeError as e:
if isinstance(v, dict):
self.unpickleable.add(str(k[0]) + str(type(v)) + str(e) + str(list(v.keys())))
else:
self.unpickleable.add(str(k[0]) + str(type(v)) + str(e)) # + str(list(v.__dict__.keys())))
except _pickle.PicklingError as e:
self.unpickleable.add(str(k[0]) + str(type(v)) + str(e))
return pickleableCache
d['cache'] = get_pickleable_dict(self.cache)
d['outargs'] = get_pickleable_dict(self.outargs)
return d
示例2: put
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def put(self, o):
"""Encode object ``o`` and write it to the pipe.
Block gevent-cooperatively until all data is written. The default
encoder is ``pickle.dumps``.
:arg o: a Python object that is encodable with the encoder of choice.
Raises:
- :exc:`GIPCError`
- :exc:`GIPCClosed`
- :exc:`pickle.PicklingError`
"""
self._validate()
with self._lock:
bindata = self._encoder(o)
self._write(struct.pack("!i", len(bindata)) + bindata)
示例3: lint
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def lint(argv: List[str]) -> None:
"""
Invoke Pylint with our preferred options
"""
print('>>>> Running pylint')
args = ['--rcfile=.pylintrc', # Load rcfile first.
'--ignored-modules=alembic,MySQLdb,flask_sqlalchemy,distutils.dist', # override ignored-modules (codacy hack)
'--load-plugins', 'pylint_quotes,pylint_monolith', # Plugins
'-f', 'parseable', # Machine-readable output.
'-j', str(configuration.get_int('pylint_threads')), # Use four cores for speed.
]
args.extend(argv or find_files(file_extension='py'))
# pylint: disable=import-outside-toplevel
import pylint.lint
try:
linter = pylint.lint.Run(args, exit=False)
except PicklingError:
print('Error while running pylint with multiprocessing')
configuration.write('pylint_threads', 1)
lint(argv)
return
if linter.linter.msg_status:
raise TestFailedException(linter.linter.msg_status)
示例4: _save_reader_to_cache
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def _save_reader_to_cache(reader, cache_file_path):
"""Save a reader object to a pickle file.
Args:
reader: The Reader instance to be persisted.
cache_file_path: A Path instance giving the path to the pickle file location.
"""
cache_path = cache_file_path.parent
os.makedirs(str(cache_path), exist_ok=True)
try:
with cache_file_path.open('wb') as cache_file:
try:
pickle.dump(reader, cache_file)
except (AttributeError, pickle.PicklingError, TypeError) as pickling_error:
log.warn("Could not pickle {} because {}".format(reader, pickling_error))
pass
except OSError as os_error:
log.warn("Could not cache {} because {}".format(reader, os_error))
示例5: test_reduce_bad_iterator
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def test_reduce_bad_iterator(self):
# Issue4176: crash when 4th and 5th items of __reduce__()
# are not iterators
class C(object):
def __reduce__(self):
# 4th item is not an iterator
return list, (), None, [], None
class D(object):
def __reduce__(self):
# 5th item is not an iterator
return dict, (), None, None, []
# Protocol 0 in Python implementation is less strict and also accepts
# iterables.
for proto in protocols:
try:
self.dumps(C(), proto)
except (AttributeError, pickle.PicklingError, cPickle.PicklingError):
pass
try:
self.dumps(D(), proto)
except (AttributeError, pickle.PicklingError, cPickle.PicklingError):
pass
示例6: get_pickling_errors
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def get_pickling_errors(self, obj, seen=None):
if seen == None:
seen = []
try:
state = obj.__getstate__()
except AttributeError:
return
if state == None:
return
if isinstance(state, tuple):
if not isinstance(state[0], dict):
state = state[1]
else:
state = state[0].update(state[1])
result = {}
for i in state:
try:
pickle.dumps(state[i], protocol=2)
except pickle.PicklingError:
if not state[i] in seen:
seen.append(state[i])
result[i] = self.get_pickling_errors(state[i], seen)
return result
示例7: save_global
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def save_global(self, obj, name=None, pack=struct.pack):
# We have to override this method in order to deal with objects
# defined interactively in IPython that are not injected in
# __main__
kwargs = dict(name=name, pack=pack)
if sys.version_info >= (3, 4):
del kwargs['pack']
try:
Pickler.save_global(self, obj, **kwargs)
except pickle.PicklingError:
Pickler.save_global(self, obj, **kwargs)
module = getattr(obj, "__module__", None)
if module == '__main__':
my_name = name
if my_name is None:
my_name = obj.__name__
mod = sys.modules[module]
if not hasattr(mod, my_name):
# IPython doesn't inject the variables define
# interactively in __main__
setattr(mod, my_name, obj)
示例8: sendFuture
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def sendFuture(self, future):
"""Send a Future to be executed remotely."""
future = copy.copy(future)
future.greenlet = None
future.children = {}
try:
if shared.getConst(hash(future.callable), timeout=0):
# Enforce name reference passing if already shared
future.callable = SharedElementEncapsulation(hash(future.callable))
self.socket.send_multipart([
TASK,
pickle.dumps(future.id, pickle.HIGHEST_PROTOCOL),
pickle.dumps(future, pickle.HIGHEST_PROTOCOL),
])
except (pickle.PicklingError, TypeError) as e:
# If element not picklable, pickle its name
# TODO: use its fully qualified name
scoop.logger.warn("Pickling Error: {0}".format(e))
future.callable = hash(future.callable)
self.socket.send_multipart([
TASK,
pickle.dumps(future.id, pickle.HIGHEST_PROTOCOL),
pickle.dumps(future, pickle.HIGHEST_PROTOCOL),
])
示例9: sendFuture
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def sendFuture(self, future):
"""Send a Future to be executed remotely."""
try:
if shared.getConst(hash(future.callable),
timeout=0):
# Enforce name reference passing if already shared
future.callable = SharedElementEncapsulation(hash(future.callable))
self.socket.send_multipart([b"TASK",
pickle.dumps(future,
pickle.HIGHEST_PROTOCOL)])
except pickle.PicklingError as e:
# If element not picklable, pickle its name
# TODO: use its fully qualified name
scoop.logger.warn("Pickling Error: {0}".format(e))
previousCallable = future.callable
future.callable = hash(future.callable)
self.socket.send_multipart([b"TASK",
pickle.dumps(future,
pickle.HIGHEST_PROTOCOL)])
future.callable = previousCallable
示例10: tryPickleOnAllContents3
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def tryPickleOnAllContents3(obj, ignore=None, path=None, verbose=False):
"""
Definitely find pickle errors
Notes
-----
In this form, this just finds one pickle error and then crashes. If you want
to make it work like the other testPickle functions and handle errors, you could.
But usually you just have to find one unpickleable SOB.
"""
with tempfile.TemporaryFile() as output:
try:
MyPickler(output).dump(obj)
except (pickle.PicklingError, TypeError):
pass
示例11: pickleRoundTrip
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def pickleRoundTrip(self, obj, name, dumper, loader, proto):
save_m = sys.modules[name]
try:
sys.modules[name] = dumper
temp = pickle.dumps(obj, proto)
sys.modules[name] = loader
result = pickle.loads(temp)
except pickle.PicklingError as pe:
# pyET must be second, because pyET may be (equal to) ET.
human = dict([(ET, "cET"), (pyET, "pyET")])
raise support.TestFailed("Failed to round-trip %r from %r to %r"
% (obj,
human.get(dumper, dumper),
human.get(loader, loader))) from pe
finally:
sys.modules[name] = save_m
return result
示例12: pickle_function
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [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_)
示例13: get_pickling_errors
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def get_pickling_errors(obj, seen=None):
if seen == None:
seen = []
try:
state = obj.__getstate__()
except AttributeError:
return
if state == None:
return
if isinstance(state, tuple):
if not isinstance(state[0], dict):
state = state[1]
else:
state = state[0].update(state[1])
result = {}
for i in state:
try:
pickle.dumps(state[i], protocol=2)
except pickle.PicklingError:
if not state[i] in seen:
seen.append(state[i])
result[i] = get_pickling_errors(state[i], seen)
return result
示例14: get_pickling_errors
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def get_pickling_errors(obj, seen=None):
if seen == None:
seen = []
try:
state = obj.__getstate__()
except AttributeError:
return
if state == None:
return
if isinstance(state, tuple):
if not isinstance(state[0], dict):
state = state[1]
else:
state = state[0].crud_instances(state[1])
result = {}
for i in state:
try:
pickle.dumps(state[i], protocol=2)
except pickle.PicklingError:
if not state[i] in seen:
seen.append(state[i])
result[i] = get_pickling_errors(state[i], seen)
return result
示例15: _read
# 需要導入模塊: import pickle [as 別名]
# 或者: from pickle import PicklingError [as 別名]
def _read(etree):
states = [CRFInfo.State._read(et) for et in
etree.findall('states/state')]
weight_groups = [CRFInfo.WeightGroup._read(et) for et in
etree.findall('weightGroups/weightGroup')]
fd = etree.find('featureDetector')
feature_detector = fd.get('name')
if fd.find('pickle') is not None:
try: feature_detector = pickle.loads(fd.find('pickle').text)
except pickle.PicklingError, e: pass # unable to unpickle it.
return CRFInfo(states,
float(etree.find('gaussianVariance').text),
etree.find('defaultLabel').text,
int(etree.find('maxIterations').text),
etree.find('transductionType').text,
weight_groups,
bool(etree.find('addStartState').text),
bool(etree.find('addEndState').text),
etree.find('modelFile').text,
feature_detector)