sys.excepthook

Here are the examples of the python api sys.excepthook taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: sugar-toolkit-gtk3
Source File: logger.py
View license
def _except_hook(exctype, value, traceback):
    # Attempt to provide verbose IPython tracebacks.
    # Importing IPython is slow, so we import it lazily.
    try:
        from IPython.ultraTB import AutoFormattedTB
        sys.excepthook = AutoFormattedTB(mode='Verbose',
                                         color_scheme='NoColor')
    except ImportError:
        sys.excepthook = sys.__excepthook__

    sys.excepthook(exctype, value, traceback)

Example 2

View license
    def run_with_api(self, code):
        """Run code with didyoumean after enabling didyoumean hook."""
        prev_hook = sys.excepthook
        self.assertEqual(prev_hook, sys.excepthook)
        didyoumean_enablehook()
        self.assertNotEqual(prev_hook, sys.excepthook)
        try:
            no_exception(code)
        except:
            last_type, last_value, last_traceback = sys.exc_info()
            sys.excepthook(last_type, last_value, last_traceback)
            raise
        finally:
            self.assertNotEqual(prev_hook, sys.excepthook)
            didyoumean_disablehook()
            self.assertEqual(prev_hook, sys.excepthook)

Example 3

Project: qutebrowser
Source File: utils.py
View license
@contextlib.contextmanager
def disabled_excepthook():
    """Run code with the exception hook temporarily disabled."""
    old_excepthook = sys.excepthook
    sys.excepthook = sys.__excepthook__
    try:
        yield
    finally:
        # If the code we did run did change sys.excepthook, we leave it
        # unchanged. Otherwise, we reset it.
        if sys.excepthook is sys.__excepthook__:
            sys.excepthook = old_excepthook

Example 4

Project: qutebrowser
Source File: test_utils.py
View license
    @pytest.fixture(autouse=True)
    def restore_excepthook(self):
        """Restore sys.excepthook and sys.__excepthook__ after tests."""
        old_excepthook = sys.excepthook
        old_dunder_excepthook = sys.__excepthook__
        yield
        sys.excepthook = old_excepthook
        sys.__excepthook__ = old_dunder_excepthook

Example 5

Project: qutebrowser
Source File: test_utils.py
View license
    def test_normal(self):
        """Test without changing sys.excepthook."""
        sys.excepthook = excepthook
        assert sys.excepthook is excepthook
        with utils.disabled_excepthook():
            assert sys.excepthook is not excepthook
        assert sys.excepthook is excepthook

Example 6

Project: qutebrowser
Source File: test_utils.py
View license
    def test_changed(self):
        """Test with changed sys.excepthook."""
        sys.excepthook = excepthook
        with utils.disabled_excepthook():
            assert sys.excepthook is not excepthook
            sys.excepthook = excepthook_2
        assert sys.excepthook is excepthook_2

Example 7

Project: bugsnag-python
Source File: client.py
View license
    def install_sys_hook(self):
        self.sys_excepthook = sys.excepthook

        def excepthook(*exc_info):
            self.excepthook(*exc_info)

            if self.sys_excepthook:
                self.sys_excepthook(*exc_info)

        sys.excepthook = excepthook
        sys.excepthook.bugsnag_client = self

Example 8

Project: bugsnag-python
Source File: test_client.py
View license
    def test_unregister_installed_except_hook(self):
        # Setup an original except hook
        def excepthook(*exc_info):
            pass
        sys.excepthook = excepthook

        client = Client()
        self.assertNotEqual(sys.excepthook, excepthook)
        client.uninstall_sys_hook()
        self.assertEqual(sys.excepthook, excepthook)

Example 9

Project: tracestack
Source File: test_tracestack.py
View license
    def test_on_off(self):
        tracestack.on()
        self.assertIsNot(sys.excepthook, sys.__excepthook__)
        self.assertTrue(isinstance(sys.excepthook, 
                                   tracestack.handler.ExceptionHandler))
        tracestack.off()
        self.assertIs(sys.excepthook, sys.__excepthook__)

Example 10

Project: tracestack
Source File: test_tracestack.py
View license
    def test_decorator(self):
        @tracestack.trace
        def buggy_function():
            self.assertIsNot(sys.excepthook, sys.__excepthook__)
            self.assertTrue(isinstance(sys.excepthook, 
                                       tracestack.handler.ExceptionHandler))
        buggy_function()
        self.assertIs(sys.excepthook, sys.__excepthook__)

        @tracestack.trace(prompt=True)
        def buggy_function_prompted():
            self.assertIsNot(sys.excepthook, sys.__excepthook__)
            self.assertTrue(isinstance(sys.excepthook, 
                                       tracestack.handler.ExceptionHandler))
        buggy_function()
        self.assertIs(sys.excepthook, sys.__excepthook__)

Example 11

View license
def _set_pm_excepthook(handle_exceptions_dict=None):
    '''
    Should be called to register the excepthook to be used.

    It's only useful for uncaught exceptions. I.e.: exceptions that go up to the excepthook.

    @param handle_exceptions: dict(exception -> ExceptionBreakpoint)
        The exceptions that should be handled.
    '''
    global _handle_exceptions
    global _original_excepthook
    if sys.excepthook != _excepthook:
        #Only keep the original if it's not our own _excepthook (if called many times).
        _original_excepthook = sys.excepthook

    _handle_exceptions = handle_exceptions_dict
    sys.excepthook = _excepthook

Example 12

Project: pygobject
Source File: helper.py
View license
@contextlib.contextmanager
def capture_exceptions():
    """Installs a temporary sys.excepthook which records all exceptions
    instead of printing them.
    """

    exceptions = []

    def custom_excepthook(*args):
        exceptions.append(ExceptionInfo(*args))

    old_hook = sys.excepthook
    sys.excepthook = custom_excepthook
    try:
        yield exceptions
    finally:
        sys.excepthook = old_hook

Example 13

Project: ipdb
Source File: __main__.py
View license
def wrap_sys_excepthook():
    # make sure we wrap it only once or we would end up with a cycle
    #  BdbQuit_excepthook.excepthook_ori == BdbQuit_excepthook
    if sys.excepthook != BdbQuit_excepthook:
        BdbQuit_excepthook.excepthook_ori = sys.excepthook
        sys.excepthook = BdbQuit_excepthook

Example 14

Project: yavide
Source File: yavide_server.py
View license
def catch_unhandled_exceptions():
    # This is what usually should be enough
    sys.excepthook = handle_exception

    # But sys.excepthook does not work anymore within multi-threaded/multi-process environment (see https://bugs.python.org/issue1230540)
    # So what we can do is to override the YavideService.run() implementation so it includes try-catch block with exceptions
    # being forwarded to the sys.excepthook function.
    run_original = YavideService.run
    def run(self):
        try:
            run_original(self)
        except:
            sys.excepthook(*sys.exc_info())
    YavideService.run = run

Example 15

View license
    def test_enable(self):
        original = sys.excepthook
        sys.excepthook = mock_excepthook
        sender = MockSynchronousSender()
        queue = channel.SynchronousQueue(sender)
        telemetry_channel = channel.TelemetryChannel(None, queue)
        exceptions.enable('foo', telemetry_channel=telemetry_channel)
        try:
            raise Exception('Boom')
        except:
            sys.excepthook(*sys.exc_info())
        sys.excepthook = original
        data = sender.data[0][0]
        self.assertIsNotNone(data)
        self.assertEqual('foo', data.ikey)
        self.assertEqual('Microsoft.ApplicationInsights.Exception', data.name)

Example 16

View license
    def test_enable(self):
        original = sys.excepthook
        sys.excepthook = mock_excepthook
        sender = MockSynchronousSender()
        queue = channel.SynchronousQueue(sender)
        telemetry_channel = channel.TelemetryChannel(None, queue)
        exceptions.enable('foo', telemetry_channel=telemetry_channel)
        try:
            raise Exception('Boom')
        except:
            sys.excepthook(*sys.exc_info())
        sys.excepthook = original
        data = sender.data[0][0]
        self.assertIsNotNone(data)
        self.assertEqual('foo', data.ikey)
        self.assertEqual('Microsoft.ApplicationInsights.Exception', data.name)

Example 17

Project: filmkodi
Source File: pydevd_breakpoints.py
View license
def _set_pm_excepthook(handle_exceptions_dict=None):
    '''
    Should be called to register the excepthook to be used.

    It's only useful for uncaught exceptions. I.e.: exceptions that go up to the excepthook.

    @param handle_exceptions: dict(exception -> ExceptionBreakpoint)
        The exceptions that should be handled.
    '''
    global _handle_exceptions
    global _original_excepthook
    if sys.excepthook != _excepthook:
        #Only keep the original if it's not our own _excepthook (if called many times).
        _original_excepthook = sys.excepthook

    _handle_exceptions = handle_exceptions_dict
    sys.excepthook = _excepthook

Example 18

Project: filmkodi
Source File: pydevd_breakpoints.py
View license
def _set_pm_excepthook(handle_exceptions_dict=None):
    '''
    Should be called to register the excepthook to be used.

    It's only useful for uncaught exceptions. I.e.: exceptions that go up to the excepthook.

    @param handle_exceptions: dict(exception -> ExceptionBreakpoint)
        The exceptions that should be handled.
    '''
    global _handle_exceptions
    global _original_excepthook
    if sys.excepthook != _excepthook:
        #Only keep the original if it's not our own _excepthook (if called many times).
        _original_excepthook = sys.excepthook

    _handle_exceptions = handle_exceptions_dict
    sys.excepthook = _excepthook

Example 19

Project: bsd-cloudinit
Source File: log.py
View license
def setup(product_name, version='unknown'):
    """Setup logging."""
    if CONF.log_config_append:
        _load_log_config(CONF.log_config_append)
    else:
        _setup_logging_from_conf(product_name, version)
    sys.excepthook = _create_logging_excepthook(product_name)

Example 20

Project: ps_mem
Source File: ps_mem.py
View license
def std_exceptions(etype, value, tb):
    sys.excepthook = sys.__excepthook__
    if issubclass(etype, KeyboardInterrupt):
        pass
    elif issubclass(etype, IOError) and value.errno == errno.EPIPE:
        pass
    else:
        sys.__excepthook__(etype, value, tb)

Example 21

Project: PokemonGo-Bot-Desktop
Source File: cgitb.py
View license
def enable(display=1, logdir=None, context=5, format="html"):
    """Install an exception handler that formats tracebacks as HTML.

    The optional argument 'display' can be set to 0 to suppress sending the
    traceback to the browser, and 'logdir' can be set to a directory to cause
    tracebacks to be written to files there."""
    sys.excepthook = Hook(display=display, logdir=logdir,
                          context=context, format=format)

Example 22

Project: pyblosxom
Source File: crashhandling.py
View license
def enable_excepthook(httpresponse=False):
    """This attaches the :ref:`CrashHandler` to the sys.excepthook.
    This will handle any exceptions thrown that don't get
    handled anywhere else.

    If you're running Pyblosxom as a WSGI application or as a CGI
    script, you should create a :ref:`CrashHandler` instance and call
    ``handle_by_response`` directly.  See
    :ref:`pyblosxom.PyblosxomWSGIApp`.
    """
    sys.excepthook = CrashHandler(httpresponse=httpresponse)

Example 23

Project: pymo
Source File: cgitb.py
View license
def enable(display=1, logdir=None, context=5, format="html"):
    """Install an exception handler that formats tracebacks as HTML.

    The optional argument 'display' can be set to 0 to suppress sending the
    traceback to the browser, and 'logdir' can be set to a directory to cause
    tracebacks to be written to files there."""
    sys.excepthook = Hook(display=display, logdir=logdir,
                          context=context, format=format)

Example 24

Project: pyqtgraph
Source File: parallelizer.py
View license
    def __exit__(self, *exc_info):
        
        if self.proc is not None:  ## worker 
            exceptOccurred = exc_info[0] is not None ## hit an exception during processing.
                
            try:
                if exceptOccurred:
                    sys.excepthook(*exc_info)
            finally:
                #print os.getpid(), 'exit'
                os._exit(1 if exceptOccurred else 0)
                
        else:  ## parent
            if self.showProgress:
                self.progressDlg.__exit__(None, None, None)

Example 25

Project: pytest-qt
Source File: exceptions.py
View license
    def finish(self):
        """Stop exception capturing, restoring the original hook.

        Can be called multiple times.
        """
        if self.old_hook is not None:
            sys.excepthook = self.old_hook
            self.old_hook = None

Example 26

Project: steve
Source File: cmdline.py
View license
def click_run():
    sys.excepthook = exception_handler
    try:
        cli(obj={})
    except ConfigNotFound as cnf:
        click.echo(VERSION)
        click.echo(cnf, err=True)

Example 27

Project: asynq
Source File: debug.py
View license
def detach_exception_hook():
    """Removes async exception hook into the sys.excepthook."""
    global is_attached, original_hook
    assert is_attached, "Async exception hook wasn't attached."
    sys.excepthook = original_hook
    is_attached = False

Example 28

Project: anaconda
Source File: __init__.py
View license
def exception_msg_handler(event, data):
    """
    Handler for the HUB_CODE_EXCEPTION message in the hubQ.

    :param event: event data
    :type event: (event_type, message_data)
    :param data: additional data
    :type data: any

    """

    # get data from the event data structure
    msg_data = event[1]

    # msg_data is a list
    sys.excepthook(*msg_data[0])

Example 29

Project: imagrium
Source File: cgitb.py
View license
def enable(display=1, logdir=None, context=5, format="html"):
    """Install an exception handler that formats tracebacks as HTML.

    The optional argument 'display' can be set to 0 to suppress sending the
    traceback to the browser, and 'logdir' can be set to a directory to cause
    tracebacks to be written to files there."""
    sys.excepthook = Hook(display=display, logdir=logdir,
                          context=context, format=format)

Example 30

Project: omnivore
Source File: exception_handler.py
View license
    def start(self):
        self.save_hook = sys.excepthook
        sys.excepthook = ExceptionHook
        
        # Probably a better way to get this info; maybe services?
        ErrorDialog.application = self.application

Example 31

Project: babble
Source File: cgitb.py
View license
def enable(display=1, logdir=None, context=5, format="html"):
    """Install an exception handler that formats tracebacks as HTML.

    The optional argument 'display' can be set to 0 to suppress sending the
    traceback to the browser, and 'logdir' can be set to a directory to cause
    tracebacks to be written to files there."""
    sys.excepthook = Hook(display=display, logdir=logdir,
                          context=context, format=format)

Example 32

Project: yum
Source File: utils.py
View license
def suppress_keyboard_interrupt_message():
    """Change settings so that nothing will be printed to the
    terminal after an uncaught :class:`exceptions.KeyboardInterrupt`.
    """
    old_excepthook = sys.excepthook

    def new_hook(type, value, traceback):
        if type != exceptions.KeyboardInterrupt:
            old_excepthook(type, value, traceback)
        else:
            pass

    sys.excepthook = new_hook

Example 33

Project: vncdotool
Source File: command.py
View license
def setup_logging(options):
    # route Twisted log messages via stdlib logging
    if options.logfile:
        handler = logging.handlers.RotatingFileHandler(options.logfile,
                                      maxBytes=5*1024*1024, backupCount=5)
        logging.getLogger().addHandler(handler)
        sys.excepthook = log_exceptions

    logging.basicConfig()
    if options.verbose > 1:
        logging.getLogger().setLevel(logging.DEBUG)
    elif options.verbose:
        logging.getLogger().setLevel(logging.INFO)

    PythonLoggingObserver().start()

Example 34

Project: OpenSesame
Source File: bug_report.py
View license
	def event_startup(self):

		"""
		desc:
			Start capturing.
		"""
		sys.excepthook = self.captured_err

Example 35

View license
    def __exit__(self, *exc_info):
        
        if self.proc is not None:  ## worker 
            exceptOccurred = exc_info[0] is not None ## hit an exception during processing.
                
            try:
                if exceptOccurred:
                    sys.excepthook(*exc_info)
            finally:
                #print os.getpid(), 'exit'
                os._exit(1 if exceptOccurred else 0)
                
        else:  ## parent
            if self.showProgress:
                self.progressDlg.__exit__(None, None, None)

Example 36

Project: synaps
Source File: log.py
View license
def setup():
    """Setup synaps logging."""
    sys.excepthook = handle_exception

    if FLAGS.log_config:
        try:
            logging.config.fileConfig(FLAGS.log_config)
        except Exception:
            traceback.print_exc()
            raise
    else:
        _setup_logging_from_flags()

Example 37

Project: MacTimeLog
Source File: log_util.py
View license
def init():
    sys.excepthook = _excepthook

    logger = logging.getLogger('mactimelog')

    if not os.path.exists(LOGGING_DIR):
        os.makedirs(LOGGING_DIR)

    handler = logging.FileHandler('{0}MacTimeLog.log'.format(LOGGING_DIR))

    formatter = logging.Formatter(LOGGING_FORMAT)
    handler.setFormatter(formatter)

    logger.addHandler(handler)
    logger.setLevel(LOGGING_LEVEL)

Example 38

Project: remotecv
Source File: error_handler.py
View license
    def install_handler(self):
        if not self.sentry_client:
            return
        old_hook = sys.excepthook
        def on_exception(type, value, traceback):
            try:
                self.sentry_client.captureException((type, value, traceback), data=self.extra_data)
            finally:
                old_hook(type, value, traceback)
        sys.excepthook = on_exception

Example 39

Project: WAPT
Source File: cgitb.py
View license
def enable(display=1, logdir=None, context=5, format="html"):
    """Install an exception handler that formats tracebacks as HTML.

    The optional argument 'display' can be set to 0 to suppress sending the
    traceback to the browser, and 'logdir' can be set to a directory to cause
    tracebacks to be written to files there."""
    sys.excepthook = Hook(display=display, logdir=logdir,
                          context=context, format=format)

Example 40

Project: imperialism-remake
Source File: server.py
View license
    def run(self):
        """
        Runs the server process by starting its own QCoreApplication.
        """
        # because PyQt5 eats exceptions in the event thread this workaround
        sys.excepthook = imperialism_remake.exception_hook

        app = QtCore.QCoreApplication([])

        # server manager, signal shutdown stops the app
        server_manager = ServerManager()
        server_manager.shutdown.connect(app.quit)
        # noinspection PyCallByClass
        QtCore.QTimer.singleShot(100, server_manager.start)

        # run event loop of app
        app.exec_()

Example 41

Project: TrustRouter
Source File: cgitb.py
View license
def enable(display=1, logdir=None, context=5, format="html"):
    """Install an exception handler that formats tracebacks as HTML.

    The optional argument 'display' can be set to 0 to suppress sending the
    traceback to the browser, and 'logdir' can be set to a directory to cause
    tracebacks to be written to files there."""
    sys.excepthook = Hook(display=display, logdir=logdir,
                          context=context, format=format)

Example 42

Project: tuskar
Source File: log.py
View license
def setup(product_name):
    """Setup logging."""
    if CONF.log_config:
        _load_log_config(CONF.log_config)
    else:
        _setup_logging_from_conf()
    sys.excepthook = _create_logging_excepthook(product_name)

Example 43

Project: bh2014
Source File: cgitb.py
View license
def enable(display=1, logdir=None, context=5, format="html"):
    """Install an exception handler that formats tracebacks as HTML.

    The optional argument 'display' can be set to 0 to suppress sending the
    traceback to the browser, and 'logdir' can be set to a directory to cause
    tracebacks to be written to files there."""
    sys.excepthook = Hook(display=display, logdir=logdir,
                          context=context, format=format)

Example 44

Project: oleviewdotnet
Source File: cgitb.py
View license
def enable(display=1, logdir=None, context=5, format="html"):
    """Install an exception handler that formats tracebacks as HTML.

    The optional argument 'display' can be set to 0 to suppress sending the
    traceback to the browser, and 'logdir' can be set to a directory to cause
    tracebacks to be written to files there."""
    sys.excepthook = Hook(display=display, logdir=logdir,
                          context=context, format=format)

Example 45

Project: vispy
Source File: wiggly_bar.py
View license
def main():
    sys.excepthook = uncaught_exceptions
    logging.basicConfig(level=logging.INFO)
    logging.getLogger().setLevel(logging.INFO)
    appQt = QtGui.QApplication(sys.argv)
    win = MainWindow()
    win.show()
    appQt.exec_()

Example 46

Project: orange
Source File: __init__.py
View license
    def tearDown(self):
        self.scene.clear()
        self.scene.deleteLater()
        self.view.deleteLater()
        del self.scene
        del self.view
        self.app.processEvents()
        del self.app
        sys.excepthook = self._orig_excepthook

Example 47

Project: orange
Source File: OWDatabasesUpdate.py
View license
    def HandleError(self, exception):
        if isinstance(exception, IOError):
            self.error(0,
                       "Could not connect to server! Press the Retry "
                       "button to try again.")
            self.SetFilesList({})
        else:
            sys.excepthook(type(exception), exception.args, None)
            self.progress.setRange(0, 0)
            self.setEnabled(True)

Example 48

Project: PythonScript
Source File: cgitb.py
View license
def enable(display=1, logdir=None, context=5, format="html"):
    """Install an exception handler that formats tracebacks as HTML.

    The optional argument 'display' can be set to 0 to suppress sending the
    traceback to the browser, and 'logdir' can be set to a directory to cause
    tracebacks to be written to files there."""
    sys.excepthook = Hook(display=display, logdir=logdir,
                          context=context, format=format)

Example 49

Project: brython
Source File: test_code_module.py
View license
    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 50

Project: bup
Source File: helpers.py
View license
def handle_ctrl_c():
    """Replace the default exception handler for KeyboardInterrupt (Ctrl-C).

    The new exception handler will make sure that bup will exit without an ugly
    stacktrace when Ctrl-C is hit.
    """
    oldhook = sys.excepthook
    def newhook(exctype, value, traceback):
        if exctype == KeyboardInterrupt:
            log('\nInterrupted.\n')
        else:
            return oldhook(exctype, value, traceback)
    sys.excepthook = newhook