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.
147 Examples
5
Example 1
Project: DidYouMean-Python Source File: didyoumean_api_tests.py
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)
5
Example 2
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
5
Example 3
Project: ipdb Source File: __main__.py
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
5
Example 4
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__)
5
Example 5
Project: PyDev.Debugger Source File: pydevd_breakpoints.py
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
5
Example 6
@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 7
Project: sugar-toolkit-gtk3 Source File: logger.py
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)
5
Example 8
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__)
5
Example 9
Project: qutebrowser Source File: utils.py
@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 10
Project: qutebrowser Source File: test_utils.py
@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 11
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
5
Example 12
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
5
Example 13
Project: bugsnag-python Source File: test_client.py
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)
5
Example 14
Project: yavide Source File: yavide_server.py
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
5
Example 15
Project: ApplicationInsights-Python Source File: TestEnable.py
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)
3
Example 16
Project: teuthology Source File: run.py
def install_except_hook():
def log_exception(exception_class, exception, traceback):
logging.critical(''.join(format_tb(traceback)))
if not exception.message:
logging.critical(exception_class.__name__)
return
logging.critical('{0}: {1}'.format(
exception_class.__name__, exception))
sys.excepthook = log_exception
3
Example 17
def install_sys_hook(self):
global __excepthook__
if __excepthook__ is None:
__excepthook__ = sys.excepthook
def handle_exception(*exc_info):
self.captureException(exc_info=exc_info)
__excepthook__(*exc_info)
sys.excepthook = handle_exception
3
Example 18
def __init__(self, sysargv, apppath, prefixpath, settingspath, libspath, i18npath, projectsroot):
self.sysargv = sysargv
self.apppath = apppath
self.prefixpath = prefixpath
self.settingspath = settingspath
self.approot = apppath
self.profileroot = apppath
self.libspath = libspath
self.i18npath = i18npath
self.app = None
self.translationFile = None
self.projectsroot = projectsroot
self._oldhook = sys.excepthook
self.sourcerun = False
3
Example 19
Project: anaconda Source File: __init__.py
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])
3
Example 20
Project: extdbg Source File: ext_traceback.py
def init_except_hook():
# # redundant code
# gExceptHook = CustomExceptHook()
# gExceptHook.add_handler(excepthook)
sys.excepthook = excepthook
3
Example 21
Project: kupfer Source File: main.py
def main():
# parse commandline before importing UI
cli_opts = get_options()
print_banner()
from kupfer import pretty
if _debug:
pretty.debug = _debug
try:
import debug
debug.install()
except ImportError:
pass
sys.excepthook = sys.__excepthook__
_set_process_title()
quiet = ("--no-splash" in cli_opts)
gtkmain(quiet)
3
Example 22
def register(reg_signal=signal.SIGQUIT, reg_unhandled=True, commands=[]):
"""
Registers exconsole hooks
:param reg_signal: if not None, register signal handler (default: ``signal.SIGQUIT``)
:param reg_unhandled: if ``True``, register unhandled exception hook (``sys.excepthook``)
:param commands: list of custom commands/objects: (<local name>, <help string>, <function or object>)
"""
if reg_signal:
signal.signal(reg_signal, handle_quit)
if reg_unhandled:
sys.excepthook = handle_exception
launch.commands = commands
3
Example 23
def Run():
'''
Wrapper to execute Wammu. Installs graphical error handler and launches
WammuApp.
'''
try:
sys.excepthook = Wammu.Error.Handler
except:
print _('Failed to set exception handler.')
app = WammuApp()
app.MainLoop()
3
Example 24
def install_sys_hook(self):
global __excepthook__
if __excepthook__ is None:
__excepthook__ = sys.excepthook
def handle_exception(*exc_info):
self.captureException(exc_info=exc_info, level='fatal')
__excepthook__(*exc_info)
handle_exception.raven_client = self
sys.excepthook = handle_exception
3
Example 25
def Init():
# Must back up old excepthook.
global old_excepthook # pylint: disable=global-statement
if old_excepthook is None:
old_excepthook = sys.excepthook
sys.excepthook = _DebugHandler
3
Example 26
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)
3
Example 27
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
3
Example 28
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_()
3
Example 29
Project: ZeroNet Source File: DebugHook.py
def handleGreenletError(self, context, type, value, tb):
if isinstance(value, str):
# Cython can raise errors where the value is a plain string
# e.g., AttributeError, "_semaphore.Semaphore has no attr", <traceback>
value = type(value)
if not issubclass(type, self.NOT_ERROR):
sys.excepthook(type, value, tb)
3
Example 30
Project: asynq Source File: debug.py
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
3
Example 31
Project: lymph Source File: service.py
def _setup_container(self, debug, loglevel):
self.container = create_container(self.config, worker=self.worker)
self.container.debug = debug
self.container.loglevel = loglevel
# Set global exception hook to send unhandled exception to the container's error_hook.
sys.excepthook = self.container.excepthook
install_plugins(self.container, self.config.get('plugins', {}))
install_interfaces(self.container, self.config.get('interfaces', {}))
for cls_name in self.args.get('--interface', ()):
cls = import_object(cls_name)
self.container.install_interface(cls)
3
Example 32
def install_excepthook(github_url):
def my_excepthook(exctype, value, tb):
s = ''.join(traceback.format_exception(exctype, value, tb))
dialog = ErrorReportDialog(None, github_url, s)
dialog.exec_()
sys.excepthook = my_excepthook
3
Example 33
Project: pyblosxom Source File: crashhandling.py
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)
3
Example 34
Project: vncdotool Source File: command.py
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()
3
Example 35
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_()
3
Example 36
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
3
Example 37
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
3
Example 38
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
3
Example 39
def event_startup(self):
"""
desc:
Start capturing.
"""
sys.excepthook = self.captured_err
3
Example 40
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)
3
Example 41
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
3
Example 42
Project: ps_mem Source File: ps_mem.py
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)
3
Example 43
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)
3
Example 44
Project: synaps Source File: log.py
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()
3
Example 45
Project: brython Source File: test_code_module.py
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__
3
Example 46
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)
3
Example 47
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)
3
Example 48
def click_run():
sys.excepthook = exception_handler
try:
cli(obj={})
except ConfigNotFound as cnf:
click.echo(VERSION)
click.echo(cnf, err=True)
3
Example 49
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)
3
Example 50
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