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