Call Python 3 raise from or emulate it for Python 2

    Args:
        exc_type (Any): Type of Exception
        message (str): Error message to display
        exc (BaseException): original exception

    Returns:
        None
176956
def raisefrom(exc_type, message, exc):
    # type: (Any, str, BaseException) -> None
    
    if sys.version_info[:2] >= (3, 2):
        six.raise_from(exc_type(message), exc)
    else:
        six.reraise(exc_type, '%s - %s' % (message, exc), sys.exc_info()[2])
812822
def _async_raise(tid, exctype):
    
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")
    print('force close: {} {}'.format(tid, datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
1139755
def _new_err(self, errclass: str, *args) -> 'Err':
        
        # get the message or exception
        ex, msg = self._get_args(*args)
        # construct the error
        # handle exception
        ftb = None  # type: str
        function = None  # type: str
        errtype = None  # type: str
        file = None  # type: str
        line = None  # type: int
        code = None  # type: str
        ex_msg = None  # type: str
        caller = None  # type: str
        caller_msg = None  # type: str

        st = inspect.stack()

        if ex is not None:
            # get info from exception
            errobj, ex_msg, tb = sys.exc_info()
            tb = traceback.extract_tb(tb)
            file, line, function, code = tb[-1]
            # if called from an external lib
            if len(tb) > 1:
                file, line, caller, code = tb[0]
            else:
                call_stack = []
                for c in st:
                    call_stack.append(c[3])
                caller = self._get_caller(call_stack, function)

            internals = [
                "err",
                "_new_err",
                "fatal",
                "warning",
                "debug",
                "info",
                "<module>"]  
            if caller == function or caller in internals:
                caller = None
            # handle messages
            if msg is not None:
                caller_msg = msg
                msg = str(ex_msg)
            else:
                msg = str(ex_msg)
            ftb = traceback.format_exc()
            errtype = errobj.__name__
        if function is None:
            # for el in st:
            #   print(el)
            function = st[3][3]
            if function == "<module>":
                function = None
        # init error object
        date = datetime.now()
        error = Err(
            function,
            date,
            msg,
            errtype,
            errclass,
            line,
            file,
            code,
            ftb,
            ex,
            caller,
            caller_msg)
        return error
254269
def set_exception(self, exception, traceback=None):
        
        if not isinstance(exception, BaseException):
            raise RuntimeError("Exception must be of BaseException type")
        self._exception = exception
        self._traceback = traceback
        self._event.set()
        self._invoke_callbacks()
321221
def raise_exception(self, exception):
        
        self.__data = None
        self.__exception = exception
        self.__event.set()
326210
def raise_error(error):
    
    exc_type = error.get('exc_type')
    if exc_type and exc_type.startswith(ERROR_PREFIX):
        exc_type = exc_type[len(ERROR_PREFIX):]
        exc_cls = ERROR_TYPE_MAP.get(exc_type, DashiError)
    else:
        exc_cls = DashiError

    raise exc_cls(**error)
34863
def _raise_exception(self, eobj, edata=None):
        """"""
        _, _, tbobj = sys.exc_info()
        if edata:
            emsg = self._format_msg(eobj["msg"], edata)
            _rwtb(eobj["type"], emsg, tbobj)
        else:
            _rwtb(eobj["type"], eobj["msg"], tbobj)
760975
def raise_error(
            self,
            exception_type,  # type: Type[Exception]
            message  # type: Text
    ):
        # type: (...) -> NoReturn
        """"""
        error_message = '{} at {}'.format(message, repr(self))
        raise exception_type(error_message)
202688
def raise_exception(self, node, exc=None, msg='', expr=None,
                        lineno=None):
        """"""
        if self.error is None:
            self.error = []
        if expr is None:
            expr = self.expr
        if len(self.error) > 0 and not isinstance(node, ast.Module):
            msg = '%s' % msg
        err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno)
        self._interrupt = ast.Break()
        self.error.append(err)
        if self.error_msg is None:
            self.error_msg = "at expr='%s'" % (self.expr)
        elif len(msg) > 0:
            self.error_msg = msg
        if exc is None:
            try:
                exc = self.error[0].exc
            except:
                exc = RuntimeError
        raise exc(self.error_msg)
420664
def error(self, exc):
        
        msg = 'trying to execute a step in the environment: \n' \
              '           - Exception: %s' % exc
        if self.logger is not None:
            self.logger.error(msg)
        self.by_console('      ERROR - %s' % msg)
1157928
def exception(self, timeout=None, do_raise=True):
    

    with self._lock:
      self.wait(timeout, do_raise=do_raise)
      if not self._exc_info:
        return None
      self._exc_retrieved = True
      if self._cancelled:
        raise self.Cancelled()
      return self._exc_info[1]
910426
def add_flow_exception(exc):
  
  global _flow_exceptions
  if not isinstance(exc, type) or not issubclass(exc, Exception):
    raise TypeError('Expected an Exception subclass, got %r' % (exc,))
  as_set = set(_flow_exceptions)
  as_set.add(exc)
  _flow_exceptions = tuple(as_set)
1024940
def base_exception_handler(*args):
    

    header, frames, trcback = format_report(*extract_exception(*args))

    LOGGER.error("!> {0}".format(Constants.logging_separators))
    map(lambda x: LOGGER.error("!> {0}".format(x)), header)

    LOGGER.error("!> {0}".format(Constants.logging_separators))
    map(lambda x: LOGGER.error("!> {0}".format(x)), frames)

    LOGGER.error("!> {0}".format(Constants.logging_separators))
    sys.stderr.write("\n".join(trcback))

    return True
1316824
def exception(  # type: ignore
        self, msg, *args, exc_info=True, **kwargs
    ) -> Task:
        
        return self.error(msg, *args, exc_info=exc_info, **kwargs)
454249
def handle_unexpected_exception(exc):
    # type: (BaseException) -> str
    
    try:
        write_logfile()
        addendum = 'Please see the log file for more information.'
    except IOError:
        addendum = 'Unable to write log file.'
    try:
        message = str(exc)
        return '{}{}{}'.format(message, '\n' if message else '', addendum)
    except Exception:  # pylint: disable=broad-except
        return str(exc)
60392
def init_soap_exception(self, exc):
        
        if not isinstance(exc, urllib2.HTTPError):
            return SoapException(unicode(exc), exc)

        if isinstance(exc, urllib2.HTTPError):
            try:
                data = exc.read()
                self.log.debug(data)

                t = SOAPpy.Parser.parseSOAP(data)
                message = '%s:%s' % (t.Fault.faultcode, t.Fault.faultstring)
                e = SoapException(message, exc)
                e.code = t.Fault.detail.Error.Code
                e.trace = t.Fault.detail.Error.Trace
                return e
            except:
                return SoapException(unicode(exc), exc)

        return SoapException(exc.reason, exc)
312341
def or_call(self, _callable, *args, **kwargs):
        
        if self._exception:
            _callable(*args, **kwargs)