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
5
Example 1
View licensedef _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)
5
Example 2
View licensedef 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)
5
Example 3
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
5
Example 4
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
5
Example 5
View licensedef 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
5
Example 6
View licensedef 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
5
Example 7
View licensedef 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
5
Example 8
View licensedef 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)
5
Example 9
View licensedef 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__)
5
Example 10
View licensedef 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__)
5
Example 11
View licensedef _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
5
Example 12
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
5
Example 13
View licensedef 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
5
Example 14
View licensedef 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
5
Example 15
View licensedef 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)
5
Example 16
View licensedef 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)
5
Example 17
View licensedef _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
5
Example 18
View licensedef _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
3
Example 19
View licensedef 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)
3
Example 20
View licensedef 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)
3
Example 21
View licensedef 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)
3
Example 22
View licensedef 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)
3
Example 23
View licensedef 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)
3
Example 24
View licensedef __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)
3
Example 25
View licensedef 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
3
Example 26
View licensedef click_run(): sys.excepthook = exception_handler try: cli(obj={}) except ConfigNotFound as cnf: click.echo(VERSION) click.echo(cnf, err=True)
3
Example 27
View licensedef 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
3
Example 28
View licensedef 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])
3
Example 29
View licensedef 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)
3
Example 30
View licensedef start(self): self.save_hook = sys.excepthook sys.excepthook = ExceptionHook # Probably a better way to get this info; maybe services? ErrorDialog.application = self.application
3
Example 31
View licensedef 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)
3
Example 32
View licensedef 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
3
Example 33
View licensedef 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()
3
Example 34
View licensedef event_startup(self): """ desc: Start capturing. """ sys.excepthook = self.captured_err
3
Example 35
View licensedef __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)
3
Example 36
View licensedef 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()
3
Example 37
View licensedef 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)
3
Example 38
View licensedef 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
3
Example 39
View licensedef 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)
3
Example 40
View licensedef 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_()
3
Example 41
View licensedef 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)
3
Example 42
View licensedef 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)
3
Example 43
View licensedef 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)
3
Example 44
View licensedef 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)
3
Example 45
View licensedef 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_()
3
Example 46
View licensedef 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
3
Example 47
View licensedef 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)
3
Example 48
View licensedef 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)
3
Example 49
View licensedef 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__
3
Example 50
View licensedef 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