本文整理汇总了Python中snakeoil.compatibility.raise_from函数的典型用法代码示例。如果您正苦于以下问题:Python raise_from函数的具体用法?Python raise_from怎么用?Python raise_from使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了raise_from函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _verify
def _verify(self, file_location, target, all_chksums=True, handlers=None):
"""
Internal function for derivatives.
Digs through chksums, and either returns None, or throws an
errors.FetchFailed exception.
- -2: file doesn't exist.
- -1: if (size chksum is available, and
file is smaller than stated chksum)
- 0: if all chksums match
- 1: if file is too large (if size chksums are available)
or else size is right but a chksum didn't match.
if all_chksums is True, all chksums must be verified; if false, all
a handler can be found for are used.
"""
nondefault_handlers = handlers
if handlers is None:
try:
handlers = get_handlers(target.chksums)
except KeyError, e:
compatibility.raise_from(
errors.FetchFailed(file_location,
"Couldn't find a required checksum handler"))
示例2: __init__
def __init__(self, location, cache_location=None, repo_id='vdb',
disable_cache=False):
prototype.tree.__init__(self, frozen=False)
self.repo_id = repo_id
self.location = location
if disable_cache:
cache_location = None
elif cache_location is None:
cache_location = pjoin("/var/cache/edb/dep", location.lstrip("/"))
self.cache_location = cache_location
self._versions_tmp_cache = {}
try:
st = os.stat(self.location)
if not stat.S_ISDIR(st.st_mode):
raise errors.InitializationError(
"base not a dir: %r" % self.location)
elif not st.st_mode & (os.X_OK|os.R_OK):
raise errors.InitializationError(
"base lacks read/executable: %r" % self.location)
except OSError as e:
if e.errno != errno.ENOENT:
compatibility.raise_from(errors.InitializationError(
"lstat failed on base %r" % self.location))
self.package_class = self.package_factory(self)
示例3: _check_magic
def _check_magic(self, fd):
fd.seek(-16, 2)
try:
pre, size, post = self.trailer.read(fd)
if pre != self.trailer_pre_magic or post != self.trailer_post_magic:
raise MalformedXpak(
"not an xpak segment, trailer didn't match: %r" % fd)
except struct.error:
raise_from(MalformedXpak(
"not an xpak segment, failed parsing trailer: %r" % fd))
# this is a bit daft, but the format seems to intentionally
# have an off by 8 in the offset address. presumably cause the
# header was added after the fact, either way we go +8 to
# check the header magic.
fd.seek(-(size + 8), 2)
self.xpak_start = fd.tell()
try:
pre, index_len, data_len = self.header.read(fd)
if pre != self.header_pre_magic:
raise MalformedXpak(
"not an xpak segment, header didn't match: %r" % fd)
except struct.error:
raise_from(MalformedXpak(
"not an xpak segment, failed parsing header: %r" % fd))
return self.xpak_start + self.header.size, index_len, data_len
示例4: get_default
def get_default(self, type_name):
"""Finds the configuration specified default obj of type_name.
Returns C{None} if no defaults.
"""
try:
defaults = self.types.get(type_name, {}).iteritems()
except compatibility.IGNORED_EXCEPTIONS:
raise
except Exception:
compatibility.raise_from(errors.ConfigurationError(
"Collapsing defaults for %r" % (type_name,)))
defaults = [(name, section) for name, section in defaults if section.default]
if not defaults:
return None
if len(defaults) > 1:
defaults = sorted([x[0] for x in defaults])
raise errors.ConfigurationError(
'type %s incorrectly has multiple default sections: %s'
% (type_name, ', '.join(map(repr, defaults))))
try:
return defaults[0][1].instantiate()
except compatibility.IGNORED_EXCEPTIONS:
raise
except Exception:
compatibility.raise_from(errors.ConfigurationError(
"Failed instantiating default %s %r" % (type_name, defaults[0][0])))
return None
示例5: add_profile
def add_profile(config, base_path, user_profile_path=None, profile_override=None):
if profile_override is None:
profile = _find_profile_link(base_path)
else:
profile = normpath(abspath(profile_override))
if not os.path.exists(profile):
raise_from(errors.ComplexInstantiationError(
"%s doesn't exist" % (profile,)))
paths = profiles.OnDiskProfile.split_abspath(profile)
if paths is None:
raise errors.ComplexInstantiationError(
'%s expands to %s, but no profile detected' %
(pjoin(base_path, 'make.profile'), profile))
if os.path.isdir(user_profile_path):
config["profile"] = basics.AutoConfigSection({
"class": "pkgcore.ebuild.profiles.UserProfile",
"parent_path": paths[0],
"parent_profile": paths[1],
"user_path": user_profile_path,
})
else:
config["profile"] = basics.AutoConfigSection({
"class": "pkgcore.ebuild.profiles.OnDiskProfile",
"basepath": paths[0],
"profile": paths[1],
})
示例6: collapse_named_section
def collapse_named_section(self, name, raise_on_missing=True):
"""Collapse a config by name, possibly returning a cached instance.
@returns: :obj:`CollapsedConfig`.
If there is no section with this name a ConfigurationError is raised,
unless raise_on_missing is False in which case None is returned.
"""
if name in self._refs:
raise errors.ConfigurationError(
'Reference to %r is recursive' % (name,))
self._refs.add(name)
try:
result = self.rendered_sections.get(name)
if result is not None:
return result
section_stack = self.sections_lookup.get(name)
if section_stack is None:
if not raise_on_missing:
return None
raise errors.ConfigurationError(
'no section called %r' % (name,))
try:
result = self.collapse_section(section_stack, name)
result.name = name
except compatibility.IGNORED_EXCEPTIONS:
raise
except Exception:
compatibility.raise_from(errors.ConfigurationError(
"Collapsing section named %r" % (name,)))
self.rendered_sections[name] = result
return result
finally:
self._refs.remove(name)
示例7: reconstruct_eclasses
def reconstruct_eclasses(self, cpv, eclass_string):
"""Turn a string from :obj:`serialize_eclasses` into a dict."""
if not isinstance(eclass_string, basestring):
raise TypeError("eclass_string must be basestring, got %r" %
eclass_string)
eclass_data = eclass_string.strip().split(self.eclass_splitter)
if eclass_data == [""]:
# occasionally this occurs in the fs backends. they suck.
return []
l = len(eclass_data)
chf_funcs = self.eclass_chf_deserializers
tuple_len = len(chf_funcs) + 1
if len(eclass_data) % tuple_len:
raise errors.CacheCorruption(
cpv, "_eclasses_ was of invalid len %i"
"(must be mod %i)" % (len(eclass_data), tuple_len))
i = iter(eclass_data)
# roughly; deserializer grabs the values it needs, resulting
# in a sequence of key/tuple pairs for each block of chfs;
# this is in turn fed into the dict kls which converts it
# to the dict.
# Finally, the first item, and that chain, is zipped into
# a dict; in effect, if 2 chfs, this results in a stream of-
# (eclass_name, ((chf1,chf1_val), (chf2, chf2_val))).
try:
return [(eclass, tuple(self._deserialize_eclass_chfs(i)))
for eclass in i]
except ValueError:
raise_from(errors.CacheCorruption(
cpv, 'ValueError reading %r' % (eclass_string,)))
示例8: existent_path
def existent_path(value):
if not os.path.exists(value):
raise ValueError("path %r doesn't exist on disk" % (value,))
try:
return osutils.abspath(value)
except EnvironmentError as e:
compatibility.raise_from(ValueError("while resolving path %r, encountered error: %r" % (value, e)))
示例9: setup_distfiles
def setup_distfiles(self):
if not self.verified_files and self.allow_fetching:
ops = self.domain.pkg_operations(self.pkg,
observer=self.observer)
if not ops.fetch():
raise format.BuildError("failed fetching required distfiles")
self.verified_files = ops._fetch_op.verified_files
if self.verified_files:
try:
if os.path.exists(self.env["DISTDIR"]):
if (os.path.isdir(self.env["DISTDIR"])
and not os.path.islink(self.env["DISTDIR"])):
shutil.rmtree(self.env["DISTDIR"])
else:
os.unlink(self.env["DISTDIR"])
except EnvironmentError as oe:
raise_from(format.FailedDirectory(
self.env["DISTDIR"],
"failed removing existing file/dir/link at: exception %s"
% oe))
if not ensure_dirs(self.env["DISTDIR"], mode=0770,
gid=portage_gid):
raise format.FailedDirectory(
示例10: convert_string
def convert_string(central, value, arg_type):
"""Conversion func for a string-based DictConfigSection."""
if not isinstance(value, basestring):
raise ValueError(
'convert_string invoked with non basestring instance:'
' val(%r), arg_type(%r)' % (value, arg_type))
if arg_type == 'callable':
try:
func = modules.load_attribute(value)
except modules.FailedImport:
compatibility.raise_from(
errors.ConfigurationError('Cannot import %r' % (value,)))
if not callable(func):
raise errors.ConfigurationError('%r is not callable' % (value,))
return func
elif arg_type.startswith('refs:'):
return list(LazyNamedSectionRef(central, arg_type, ref)
for ref in str_to_list(value))
elif arg_type.startswith('ref:'):
return LazyNamedSectionRef(central, arg_type, str_to_str(value))
elif arg_type == 'repr':
return 'str', value
func = _str_converters.get(arg_type)
if func is None:
raise errors.ConfigurationError('Unknown type %r' % (arg_type,))
return func(value)
示例11: keys_dict
def keys_dict(self):
fd = self._fd
index_start, index_len, data_len = self._check_magic(fd)
data_start = index_start + index_len
keys_dict = OrderedDict()
key_rewrite = self._reading_key_rewrites.get
while index_len:
key_len = struct.unpack(">L", fd.read(4))[0]
key = fd.read(key_len)
if compatibility.is_py3k:
key = key.decode('ascii')
if len(key) != key_len:
raise MalformedXpak(
"tried reading key %i of len %i, but hit EOF" % (
len(keys_dict) + 1, key_len))
try:
offset, data_len = struct.unpack(">LL", fd.read(8))
except struct.error:
raise_from(MalformedXpak(
"key %i, tried reading data offset/len but hit EOF" % (
len(keys_dict) + 1)))
key = key_rewrite(key, key)
keys_dict[key] = (
data_start + offset, data_len,
compatibility.is_py3k and not key.startswith("environment"))
index_len -= (key_len + 12) # 12 for key_len, offset, data_len longs
return keys_dict
示例12: instantiate
def instantiate(self):
if self._instance is None:
try:
self._instance = self._instantiate()
except compatibility.IGNORED_EXCEPTIONS:
raise
except Exception, e:
compatibility.raise_from(errors.InstantiationError(self.name))
示例13: convert_to_restrict
def convert_to_restrict(sequence, default=packages.AlwaysTrue):
"""Convert an iterable to a list of atoms, or return the default"""
l = []
try:
for x in sequence:
l.append(parserestrict.parse_match(x))
except parserestrict.ParseError, e:
compatibility.raise_from(optparse.OptionValueError("arg %r isn't a valid atom: %s" % (x, e)))
示例14: _sync
def _sync(self, verbosity, output_fd):
try:
st = os.stat(self.basedir)
except EnvironmentError, ie:
if ie.errno != errno.ENOENT:
compatibility.raise_from(generic_exception(self, self.basedir, ie))
command = self._initial_pull()
chdir = None
示例15: _delitem
def _delitem(self, cpv):
try:
os.remove(pjoin(self.location, cpv))
except OSError as e:
if e.errno == errno.ENOENT:
raise KeyError(cpv)
else:
raise_from(errors.CacheCorruption(cpv, e))