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


Python six.reraise方法代码示例

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


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

示例1: raise_for_status

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def raise_for_status(self, allow_redirects=True):
        """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""

        if self.status_code == 304:
            return
        elif self.error:
            if self.traceback:
                six.reraise(Exception, Exception(self.error), Traceback.from_string(self.traceback).as_traceback())
            http_error = HTTPError(self.error)
        elif (self.status_code >= 300) and (self.status_code < 400) and not allow_redirects:
            http_error = HTTPError('%s Redirection' % (self.status_code))
        elif (self.status_code >= 400) and (self.status_code < 500):
            http_error = HTTPError('%s Client Error' % (self.status_code))
        elif (self.status_code >= 500) and (self.status_code < 600):
            http_error = HTTPError('%s Server Error' % (self.status_code))
        else:
            return

        http_error.response = self
        raise http_error 
开发者ID:binux,项目名称:pyspider,代码行数:22,代码来源:response.py

示例2: file_from_module_name

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def file_from_module_name(self, modname, contextfile):
        try:
            value = self._mod_file_cache[(modname, contextfile)]
            traceback = sys.exc_info()[2]
        except KeyError:
            try:
                value = modutils.file_info_from_modpath(
                    modname.split('.'), context_file=contextfile)
                traceback = sys.exc_info()[2]
            except ImportError as ex:
                value = exceptions.AstroidImportError(
                    'Failed to import module {modname} with error:\n{error}.',
                    modname=modname, error=ex)
                traceback = sys.exc_info()[2]
            self._mod_file_cache[(modname, contextfile)] = value
        if isinstance(value, exceptions.AstroidBuildingError):
            six.reraise(exceptions.AstroidBuildingError,
                        value, traceback)
        return value 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:21,代码来源:manager.py

示例3: set

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def set(self, key, value, namespace=None, serializer=None, metadata=None):
        """
        Set the value of a key.

        Args:
            key (str): The key for which `value` should be stored.
            value (object): The value to be stored.
            namespace (str, None): The namespace to be used.
            serializer (Serializer): The `Serializer` subclass to use for the
                serialisation of value into the cache. (default=PickleSerializer)
            metadata (dict, None): Additional metadata to be stored with the value
                in the cache. Values must be serializable via `yaml.safe_dump`.
        """
        namespace, key = self._namespace(namespace), self._key(key)
        serializer = serializer or PickleSerializer()
        try:
            with self._get_stream_for_key(namespace, key, 'data{}'.format(serializer.file_extension), mode='wb', create=True) as fh:
                serializer.serialize(value, fh)
            self.set_metadata(key, metadata, namespace=namespace, replace=True)
        except:
            self.unset(key, namespace=namespace)
            six.reraise(*sys.exc_info()) 
开发者ID:airbnb,项目名称:omniduct,代码行数:24,代码来源:base.py

示例4: join

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def join(self, timeout=None, suppress_exception=False):
        """
        Join the thread.  If target raised an exception, re-raise it.
        Otherwise, return the value returned by target.

        :param timeout: Timeout value to pass to threading.Thread.join().
        :param suppress_exception: If True, don't re-raise the exception.
        """
        threading.Thread.join(self, timeout)
        try:
            if self._e:
                if not suppress_exception:
                    # Because the exception was raised in another thread, we
                    # need to explicitly insert the current context into it
                    s = error_context.exception_context(self._e[1])
                    s = error_context.join_contexts(error_context.get_context(), s)
                    error_context.set_exception_context(self._e[1], s)
                    six.reraise(*self._e)
            else:
                return self._retval
        finally:
            # Avoid circular references (join() may be called multiple times
            # so we can't delete these)
            self._e = None
            self._retval = None 
开发者ID:avocado-framework,项目名称:avocado-vt,代码行数:27,代码来源:utils_misc.py

示例5: import_string

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def import_string(dotted_path):
    """
    Import a dotted module path and return the attribute/class designated by the
    last name in the path. Raise ImportError if the import failed.
    Backported from Django 1.7
    """
    try:
        module_path, class_name = dotted_path.rsplit('.', 1)
    except ValueError:
        msg = "%s doesn't look like a module path" % dotted_path
        six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])

    module = import_module(module_path)

    try:
        return getattr(module, class_name)
    except AttributeError:
        msg = 'Module "%s" does not define a "%s" attribute/class' % (
            dotted_path, class_name)
        six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) 
开发者ID:arteria,项目名称:django-compat,代码行数:22,代码来源:__init__.py

示例6: convert_exceptions

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def convert_exceptions(function, exception_map):
    expected_exceptions = tuple(exception_map.keys())

    @functools.wraps(function)
    def wrapper(*args, **kwargs):
        try:
            return function(*args, **kwargs)
        except expected_exceptions as ex:
            raised_exception = exception_map.get(type(ex))
            if not raised_exception:
                # exception might be a subclass of an expected exception.
                for expected in expected_exceptions:
                    if isinstance(ex, expected):
                        raised_exception = exception_map[expected]
                        break

            exc_info = sys.exc_info()
            # NOTE(claudiub): Python 3 raises the exception object given as
            # the second argument in six.reraise.
            # The original message will be maintained by passing the original
            # exception.
            exc = raised_exception(six.text_type(exc_info[1]))
            six.reraise(raised_exception, exc, exc_info[2])
    return wrapper 
开发者ID:openstack,项目名称:compute-hyperv,代码行数:26,代码来源:driver.py

示例7: wrap_exception

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def wrap_exception(self, event_args, *args, **kwargs):
        next_handler = event_args.pop("next_handler")
        if not next_handler:
            return
        try:
            return next_handler.invoke(event_args, *args, **kwargs)
        except Exception as e:
            if isinstance(e, CloudBridgeBaseException):
                raise
            else:
                ex_type, ex_value, traceback = sys.exc_info()
                cb_ex = CloudBridgeBaseException(
                    "CloudBridgeBaseException: {0} from exception type: {1}"
                    .format(ex_value, ex_type))
                if sys.version_info >= (3, 0):
                    six.raise_from(cb_ex, e)
                else:
                    six.reraise(CloudBridgeBaseException, cb_ex, traceback) 
开发者ID:CloudVE,项目名称:cloudbridge,代码行数:20,代码来源:middleware.py

示例8: get

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def get(self):
        """Creates a generator to extract data from the queue.

        Skip the data if it is `None`.

        # Yields
            The next element in the queue, i.e. a tuple
            `(inputs, targets)` or
            `(inputs, targets, sample_weights)`.
        """
        try:
            while self.is_running():
                inputs = self.queue.get(block=True).get()
                self.queue.task_done()
                if inputs is not None:
                    yield inputs
        except Exception as e:
            self.stop()
            six.reraise(*sys.exc_info()) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:21,代码来源:data_utils.py

示例9: __iter__

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def __iter__(self):
    """Iterate over the process function and finalize the log directory."""
    try:
      args = self._init_fn and self._init_fn(self._logdir)
      if args is None:
        args = ()
      if not isinstance(args, tuple):
        args = (args,)
      for value in self._process_fn(self._logdir, *args):
        if not self._running[0]:
          break
        yield value
      self._logger.info('Done.')
      self._store_done()
    except WorkerConflict:
      self._logging.warn('Unexpected takeover.')
      raise SkipRun
    except Exception as e:
      exc_info = sys.exc_info()
      self._handle_exception(e)
      six.reraise(*exc_info)
    finally:
      self._running[0] = False
      self._thread and self._thread.join() 
开发者ID:google-research,项目名称:planet,代码行数:26,代码来源:running.py

示例10: join

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def join(self, timeout=None):
        """Blocks until the thread has finished.

        If the thread also raised an uncaught exception, this method will raise that same exception.

        Note, the only way to tell for sure that the thread finished is by invoking 'is_alive' after this
        method returns.  If the thread is still alive, that means this method exited due to a timeout expiring.

        @param timeout: The number of seconds to wait for the thread to finish or None if it should block
            indefinitely.
        @type timeout: float|None
        """
        threading.Thread.join(self, timeout)
        if not self.isAlive() and self.__exception_info is not None:
            six.reraise(
                self.__exception_info[0],
                self.__exception_info[1],
                self.__exception_info[2],
            ) 
开发者ID:scalyr,项目名称:scalyr-agent-2,代码行数:21,代码来源:util.py

示例11: parse_content

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def parse_content(self, content):
        try:
            if type(content) is list:
                self.data = yaml.load('\n'.join(content), Loader=SafeLoader)
            else:
                self.data = yaml.load(content, Loader=SafeLoader)
            if self.data is None:
                raise SkipException("There is no data")
            if not isinstance(self.data, (dict, list)):
                raise ParseException("YAML didn't produce a dictionary or list.")
        except SkipException as se:
            tb = sys.exc_info()[2]
            six.reraise(SkipException, SkipException(str(se)), tb)
        except:
            tb = sys.exc_info()[2]
            cls = self.__class__
            name = ".".join([cls.__module__, cls.__name__])
            msg = "%s couldn't parse yaml." % name
            six.reraise(ParseException, ParseException(msg), tb) 
开发者ID:RedHatInsights,项目名称:insights-core,代码行数:21,代码来源:__init__.py

示例12: augment_exception_message_and_reraise

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def augment_exception_message_and_reraise(exception, message):
  """Reraises `exception`, appending `message` to its string representation."""

  class ExceptionProxy(type(exception)):
    """Acts as a proxy for an exception with an augmented message."""
    __module__ = type(exception).__module__

    def __init__(self):
      pass

    def __getattr__(self, attr_name):
      return getattr(exception, attr_name)

    def __str__(self):
      return str(exception) + message

  ExceptionProxy.__name__ = type(exception).__name__

  proxy = ExceptionProxy()
  if six.PY3:
    ExceptionProxy.__qualname__ = type(exception).__qualname__
    six.raise_from(proxy.with_traceback(exception.__traceback__), None)
  else:
    six.reraise(proxy, None, sys.exc_info()[2]) 
开发者ID:google,项目名称:gin-config,代码行数:26,代码来源:utils.py

示例13: import_string

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def import_string(dotted_path):
    """
    Import a dotted module path and return the attribute/class designated by the
    last name in the path. Raise ImportError if the import failed.

    (stolen from Django)
    """
    try:
        module_path, class_name = dotted_path.rsplit('.', 1)
    except ValueError:
        msg = "{} doesn't look like a module path".format(dotted_path)
        six.reraise(ImportError, ImportError(msg), sys.exc_info()[2])

    module = import_module(module_path)
    try:
        return getattr(module, class_name)
    except AttributeError:
        msg = 'Module "{}" does not define a "{}" attribute/class'.format(module_path, class_name)
        six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) 
开发者ID:eht16,项目名称:python-logstash-async,代码行数:21,代码来源:utils.py

示例14: reraise

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def reraise(self):
        reraise(self.exc_type, self.exc_value, self.traceback) 
开发者ID:pywren,项目名称:pywren-ibm-cloud,代码行数:4,代码来源:decorators.py

示例15: reraise

# 需要导入模块: import six [as 别名]
# 或者: from six import reraise [as 别名]
def reraise(exception):
    '''Reraises an exception with the traceback from the current exception
    block.'''
    six.reraise(type(exception), exception, sys.exc_info()[2]) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:6,代码来源:util.py


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