Python sys.__excepthook__() Examples

The following are 30 code examples of sys.__excepthook__(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: utils.py    From ms_deisotope with Apache License 2.0 6 votes vote down vote up
def register_debug_hook():
    import traceback

    def info(type, value, tb):
        if hasattr(sys, 'ps1') or not sys.stderr.isatty():
            sys.__excepthook__(type, value, tb)
        else:
            try:
                import ipdb as pdb_api
            except ImportError:
                import pdb as pdb_api
            traceback.print_exception(type, value, tb)
            pdb_api.post_mortem(tb)

    sys.excepthook = info
    logging.basicConfig(level="DEBUG") 
Example #2
Source File: __init__.py    From pyleecan with Apache License 2.0 6 votes vote down vote up
def my_excepthook(type, value, tback):
    """When an exception occurs: Log the error and continue (doesn't kill the
    GUI)

    Parameters
    ----------
    type :

    value :

    tback :


    Returns
    -------

    """
    # log the exception here (Not needed with stderr redirect)

    # then call the default handler
    sys.__excepthook__(type, value, tback) 
Example #3
Source File: test_exceptions.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_unhandled(self):
        # Check for sensible reporting of unhandled exceptions
        for exc_type in (ValueError, BrokenStrException):
            try:
                exc = exc_type("test message")
                # The following line is included in the traceback report:
                raise exc
            except exc_type:
                with captured_stderr() as stderr:
                    sys.__excepthook__(*sys.exc_info())
            report = stderr.getvalue()
            self.assertIn("test_exceptions.py", report)
            self.assertIn("raise exc", report)
            self.assertIn(exc_type.__name__, report)
            if exc_type is BrokenStrException:
                self.assertIn("<exception str() failed>", report)
            else:
                self.assertIn("test message", report)
            self.assertTrue(report.endswith("\n")) 
Example #4
Source File: logs.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def uncaught_exception_handler(exception_type, exception_value,
                               exception_traceback):
  """Handles any exception that are uncaught by logging an error and calling
  the sys.__excepthook__."""
  # Ensure that we are not calling ourself. This shouldn't be needed since we
  # are using sys.__excepthook__. Do this check anyway since if we are somehow
  # calling ourself we might infinitely send errors to the logs, which would be
  # quite bad.
  global _is_already_handling_uncaught
  if _is_already_handling_uncaught:
    raise Exception('Loop in uncaught_exception_handler')
  _is_already_handling_uncaught = True

  # Use emit since log_error needs sys.exc_info() to return this function's
  # arguments to call init properly.
  # Don't worry about emit() throwing an Exception, python will let us know
  # about that exception as well as the original one.
  emit(
      logging.ERROR,
      'Uncaught exception',
      exc_info=(exception_type, exception_value, exception_traceback))

  sys.__excepthook__(exception_type, exception_value, exception_traceback) 
Example #5
Source File: code.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        sys.last_type, sys.last_value, last_tb = ei = sys.exc_info()
        sys.last_traceback = last_tb
        try:
            lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next)
            if sys.excepthook is sys.__excepthook__:
                self.write(''.join(lines))
            else:
                # If someone has set sys.excepthook, we let that take precedence
                # over self.write
                sys.excepthook(ei[0], ei[1], last_tb)
        finally:
            last_tb = ei = None 
Example #6
Source File: self_learn.py    From nonauto-nmt with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def interactive_exception(e_class, e_value, tb):
    sys.__excepthook__(e_class, e_value, tb)
    tb_stack = extract_tb(tb)
    locals_stack = []
    while tb is not None:
        locals_stack.append(tb.tb_frame.f_locals)
        tb = tb.tb_next
    while len(tb_stack) > 0:
        frame = tb_stack.pop()
        ls = locals_stack.pop()
        print('\nInterpreter at file "{}", line {}, in {}:'.format(
            frame.filename, frame.lineno, frame.name))
        print('  {}'.format(frame.line.strip()))
        interact(local=ls)
#sys.excepthook = interactive_exception

# check dirs 
Example #7
Source File: code.py    From Imogen with MIT License 6 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        sys.last_type, sys.last_value, last_tb = ei = sys.exc_info()
        sys.last_traceback = last_tb
        try:
            lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next)
            if sys.excepthook is sys.__excepthook__:
                self.write(''.join(lines))
            else:
                # If someone has set sys.excepthook, we let that take precedence
                # over self.write
                sys.excepthook(ei[0], ei[1], last_tb)
        finally:
            last_tb = ei = None 
Example #8
Source File: pydevd_console.py    From PyDev.Debugger with Eclipse Public License 1.0 6 votes vote down vote up
def runcode(self, code):
        """Execute a code object.

        When an exception occurs, self.showtraceback() is called to
        display a traceback.  All exceptions are caught except
        SystemExit, which is reraised.

        A note about KeyboardInterrupt: this exception may occur
        elsewhere in this code, and may not always be caught.  The
        caller should be prepared to deal with it.

        """
        try:
            Exec(code, self.frame.f_globals, self.frame.f_locals)
            pydevd_save_locals.save_locals(self.frame)
        except SystemExit:
            raise
        except:
            # In case sys.excepthook called, use original excepthook #PyDev-877: Debug console freezes with Python 3.5+
            # (showtraceback does it on python 3.5 onwards)
            sys.excepthook = sys.__excepthook__
            try:
                self.showtraceback()
            finally:
                sys.__excepthook__ = sys.excepthook 
Example #9
Source File: main_window.py    From CQ-editor with Apache License 2.0 6 votes vote down vote up
def setup_logging(self):

        from logbook.compat import redirect_logging
        from logbook import INFO, Logger

        redirect_logging()
        self.components['log'].handler.level = INFO
        self.components['log'].handler.push_application()

        self._logger = Logger(self.name)

        def handle_exception(exc_type, exc_value, exc_traceback):

            if issubclass(exc_type, KeyboardInterrupt):
                sys.__excepthook__(exc_type, exc_value, exc_traceback)
                return

            self._logger.error("Uncaught exception occurred",
                               exc_info=(exc_type, exc_value, exc_traceback))

        sys.excepthook = handle_exception 
Example #10
Source File: test_sys.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_original_excepthook(self):
        err = io.StringIO()
        sys.stderr = err

        eh = sys.__excepthook__

        self.assertRaises(TypeError, eh)
        try:
            raise ValueError(42)
        except ValueError as exc:
            eh(*sys.exc_info())

        self.assertTrue(err.getvalue().endswith("ValueError: 42\n")) 
Example #11
Source File: pychemqt.py    From pychemqt with GNU General Public License v3.0 5 votes vote down vote up
def exceptfunction(error, msg, traceback):
    sys.__excepthook__(error, msg, traceback) 
Example #12
Source File: debug.py    From Jacinle with MIT License 5 votes vote down vote up
def _custom_exception_hook(type, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like
        # device, so we call the default hook
        sys.__excepthook__(type, value, tb)
    else:
        import traceback, ipdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type, value, tb)
        # ...then start the debugger in post-mortem mode.
        ipdb.post_mortem(tb) 
Example #13
Source File: save_engine.py    From raisetheempires with GNU General Public License v3.0 5 votes vote down vote up
def exception_handler(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
    if crash_log:
        text = editor.edit(filename=os.path.join(log_path(), "log.txt"))

# logger = logging.getLogger(__name__)
# handler = logging.StreamHandler(stream=sys.stdout)
# logger.addHandler(handler) 
Example #14
Source File: test_log.py    From oslo.log with Apache License 2.0 5 votes vote down vote up
def test_excepthook_installed(self):
        log.setup(self.CONF, "test_excepthook_installed")
        self.assertTrue(sys.excepthook != sys.__excepthook__) 
Example #15
Source File: exchange_errors.py    From catalyst with Apache License 2.0 5 votes vote down vote up
def silent_except_hook(exctype, excvalue, exctraceback):
    if exctype in [PricingDataBeforeTradingError, PricingDataNotLoadedError,
                   SymbolNotFoundOnExchange, NoDataAvailableOnExchange,
                   ExchangeAuthEmpty]:
        fn = traceback.extract_tb(exctraceback)[-1][0]
        ln = traceback.extract_tb(exctraceback)[-1][1]
        print("Error traceback: {1} (line {2})\n"
              "{0.__name__}:  {3}".format(exctype, fn, ln, excvalue))
    else:
        sys.__excepthook__(exctype, excvalue, exctraceback) 
Example #16
Source File: code.py    From Imogen with MIT License 5 votes vote down vote up
def showsyntaxerror(self, filename=None):
        """Display the syntax error that just occurred.

        This doesn't display a stack trace because there isn't one.

        If a filename is given, it is stuffed in the exception instead
        of what was there before (because Python's parser always uses
        "<string>" when reading from a string).

        The output is written by self.write(), below.

        """
        type, value, tb = sys.exc_info()
        sys.last_type = type
        sys.last_value = value
        sys.last_traceback = tb
        if filename and type is SyntaxError:
            # Work hard to stuff the correct filename in the exception
            try:
                msg, (dummy_filename, lineno, offset, line) = value.args
            except ValueError:
                # Not the format we expect; leave it alone
                pass
            else:
                # Stuff in the right filename
                value = SyntaxError(msg, (filename, lineno, offset, line))
                sys.last_value = value
        if sys.excepthook is sys.__excepthook__:
            lines = traceback.format_exception_only(type, value)
            self.write(''.join(lines))
        else:
            # If someone has set sys.excepthook, we let that take precedence
            # over self.write
            sys.excepthook(type, value, tb) 
Example #17
Source File: marketplace_errors.py    From catalyst with Apache License 2.0 5 votes vote down vote up
def silent_except_hook(exctype, excvalue, exctraceback):
    if exctype in [MarketplacePubAddressEmpty, MarketplaceDatasetNotFound,
                   MarketplaceNoAddressMatch, MarketplaceHTTPRequest,
                   MarketplaceNoCSVFiles, MarketplaceContractDataNoMatch,
                   MarketplaceSubscriptionExpired, MarketplaceJSONError,
                   MarketplaceWalletNotSupported, MarketplaceEmptySignature,
                   MarketplaceRequiresPython3]:
        fn = traceback.extract_tb(exctraceback)[-1][0]
        ln = traceback.extract_tb(exctraceback)[-1][1]
        print("Error traceback: {1} (line {2})\n"
              "{0.__name__}:  {3}".format(exctype, fn, ln, excvalue))
    else:
        sys.__excepthook__(exctype, excvalue, exctraceback) 
Example #18
Source File: utils.py    From everest with MIT License 5 votes vote down vote up
def ExceptionHookPDB(exctype, value, tb):
    '''
    A custom exception handler, with :py:obj:`pdb` post-mortem for debugging.

    '''

    for line in traceback.format_exception_only(exctype, value):
        log.error(line.replace('\n', ''))
    for line in traceback.format_tb(tb):
        log.error(line.replace('\n', ''))
    sys.__excepthook__(exctype, value, tb)
    pdb.pm() 
Example #19
Source File: facade.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def _prevent_dpkg_apport_error(self, exc_type, exc_obj, exc_tb):
        """Prevent dpkg errors from generating Apport crash reports.

        When dpkg reports an error, a SystemError is raised and cleaned
        up in C code. However, it seems like the Apport except hook is
        called before the C code clears the error, generating crash
        reports even though nothing crashed.

        This exception hook doesn't call the Apport hook for
        SystemErrors, but it calls it for all other errors.
        """
        if exc_type is SystemError:
            sys.__excepthook__(exc_type, exc_obj, exc_tb)
            return
        self.old_excepthook(exc_type, exc_obj, exc_tb) 
Example #20
Source File: test_code_module.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def mock_sys(self):
        "Mock system environment for InteractiveConsole"
        # use exit stack to match patch context managers to addCleanup
        stack = ExitStack()
        self.addCleanup(stack.close)
        self.infunc = stack.enter_context(mock.patch('code.input',
                                          create=True))
        self.stdout = stack.enter_context(mock.patch('code.sys.stdout'))
        self.stderr = stack.enter_context(mock.patch('code.sys.stderr'))
        prepatch = mock.patch('code.sys', wraps=code.sys, spec=code.sys)
        self.sysmod = stack.enter_context(prepatch)
        if sys.excepthook is sys.__excepthook__:
            self.sysmod.excepthook = self.sysmod.__excepthook__ 
Example #21
Source File: start_test.py    From abnormal-spatiotemporal-ae with GNU General Public License v3.0 5 votes vote down vote up
def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        logger.warning("Ctrl + C triggered by user, testing ended prematurely")
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    logger.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)) 
Example #22
Source File: code.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def showsyntaxerror(self, filename=None):
        """Display the syntax error that just occurred.

        This doesn't display a stack trace because there isn't one.

        If a filename is given, it is stuffed in the exception instead
        of what was there before (because Python's parser always uses
        "<string>" when reading from a string).

        The output is written by self.write(), below.

        """
        type, value, tb = sys.exc_info()
        sys.last_type = type
        sys.last_value = value
        sys.last_traceback = tb
        if filename and type is SyntaxError:
            # Work hard to stuff the correct filename in the exception
            try:
                msg, (dummy_filename, lineno, offset, line) = value.args
            except ValueError:
                # Not the format we expect; leave it alone
                pass
            else:
                # Stuff in the right filename
                value = SyntaxError(msg, (filename, lineno, offset, line))
                sys.last_value = value
        if sys.excepthook is sys.__excepthook__:
            lines = traceback.format_exception_only(type, value)
            self.write(''.join(lines))
        else:
            # If someone has set sys.excepthook, we let that take precedence
            # over self.write
            sys.excepthook(type, value, tb) 
Example #23
Source File: crashreporter.py    From crashreporter with MIT License 5 votes vote down vote up
def forward_exception(self, etype, evalue, tb):
        """
        Forward the exception onto the backup copy that was made of the sys.__excepthook__

        :param etype: Exceoption type
        :param evalue: Exception value
        :param tb: Traceback
        :return:
        """
        self._excepthook(etype, evalue, tb) 
Example #24
Source File: _control.py    From scoop with GNU Lesser General Public License v3.0 5 votes vote down vote up
def advertiseBrokerWorkerDown(exctype, value, traceback):
    """Hook advertizing the broker if an impromptu shutdown is occuring."""
    if not scoop.SHUTDOWN_REQUESTED:
        execQueue.shutdown()
    sys.__excepthook__(exctype, value, traceback) 
Example #25
Source File: main.py    From Blender-Version-Manager with GNU General Public License v3.0 5 votes vote down vote up
def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    utcnow = strftime(('%Y-%m-%d_%H-%M-%S'), gmtime())
    logging.basicConfig(filename="BVM_Report_" + utcnow +
                        ".log", level=logging.DEBUG)
    logger.error("Uncaught exception", exc_info=(
        exc_type, exc_value, exc_traceback)) 
Example #26
Source File: global_except_hook.py    From chainer with MIT License 5 votes vote down vote up
def _global_except_hook(exctype, value, traceback):
    """Catches an unhandled exception and call MPI_Abort()."""
    try:
        if _orig_except_hook:
            _orig_except_hook(exctype, value, traceback)
        else:
            sys.__excepthook__(exctype, value, traceback)

    finally:
        import mpi4py.MPI
        rank = mpi4py.MPI.COMM_WORLD.Get_rank()
        sys.stderr.write('\n')
        sys.stderr.write('******************************************\n')
        sys.stderr.write('ChainerMN:\n')
        sys.stderr.write('   Uncaught exception on rank {}.\n'.format(rank))
        sys.stderr.write('   Calling MPI_Abort() to shut down MPI...\n')
        sys.stderr.write('******************************************\n')
        sys.stderr.write('\n\n')
        sys.stderr.flush()

        try:
            import mpi4py.MPI
            mpi4py.MPI.COMM_WORLD.Abort(1)
        except Exception as e:
            # Something is completely broken...
            # There's nothing we can do any more
            sys.stderr.write(
                'Sorry, failed to stop MPI and the process may hang.\n')
            sys.stderr.flush()
            raise e 
Example #27
Source File: debugger.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def debug(method, *args, **kwargs):
    """Run the method and debug any exception, except syntax or user
    interrupt.
    """
    try:
        method(*args, **kwargs)
    except:
        ex, val, tb = sys.exc_info()
        if ex in (SyntaxError, IndentationError, KeyboardInterrupt):
            sys.__excepthook__(ex, val, tb)
        else:
            post_mortem(tb, ex, val) 
Example #28
Source File: debugger.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def debug(method, *args, **kwargs):
    """Run the method and debug any exception, except syntax or user
    interrupt.
    """
    try:
        method(*args, **kwargs)
    except:
        ex, val, tb = sys.exc_info()
        if ex in (SyntaxError, IndentationError, KeyboardInterrupt):
            sys.__excepthook__(ex, val, tb)
        else:
            post_mortem(tb, ex, val) 
Example #29
Source File: autodebug.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def debugger_hook(exc, value, tb):
        if (not hasattr(sys.stderr, "isatty") or
            not sys.stderr.isatty() or exc in (SyntaxError, IndentationError, KeyboardInterrupt)):
            # We don't have a tty-like device, or it was a SyntaxError, so
            # call the default hook.
            sys.__excepthook__(exc, value, tb)
        else:
            from pycopia import debugger
            debugger.post_mortem(tb, exc, value) 
Example #30
Source File: autodebug.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def debugger_hook(exc, value, tb):
        if (not hasattr(sys.stderr, "isatty") or
            not sys.stderr.isatty() or exc in (SyntaxError, IndentationError, KeyboardInterrupt)):
            sys.__excepthook__(exc, value, tb)
        else:
            from pycopia.fepy import debugger
            debugger.post_mortem(tb, exc, value)