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: link.py    From D-VAE with MIT License 6 votes vote down vote up
def thunk_hook(type, value, trace):
    """
    WRITEME

    This function is meant to replace excepthook and do some
    special work if the exception value has a __thunk_trace__
    field. In that case, it retrieves the field, which should
    contain a trace as returned by L{traceback.extract_stack},
    and prints it out on L{stderr}.

    The normal excepthook is then called.

    Notes
    -----
    This hook replaced by nosetests, so it does not run in nose tests.

    """
    log_thunk_trace(value)
    __excepthook(type, value, trace) 
Example #2
Source File: excepthook.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _make_excepthook(old_excepthook):
    # type: (Excepthook) -> Excepthook
    def sentry_sdk_excepthook(type_, value, traceback):
        # type: (Type[BaseException], BaseException, TracebackType) -> None
        hub = Hub.current
        integration = hub.get_integration(ExcepthookIntegration)

        if integration is not None and _should_send(integration.always_run):
            # If an integration is there, a client has to be there.
            client = hub.client  # type: Any

            with capture_internal_exceptions():
                event, hint = event_from_exception(
                    (type_, value, traceback),
                    client_options=client.options,
                    mechanism={"type": "excepthook", "handled": False},
                )
                hub.capture_event(event, hint=hint)

        return old_excepthook(type_, value, traceback)

    return sentry_sdk_excepthook 
Example #3
Source File: main_gui.py    From simnibs with GNU General Public License v3.0 6 votes vote down vote up
def start_gui(args):
    app = QtWidgets.QApplication(args)
    #app.setAttribute(QtCore.Qt.AA_UseDesktopOpenGL)
    #app.setAttribute(QtCore.Qt.AA_UseSoftwareOpenGL)
    #app.setAttribute(QtCore.Qt.AA_UseOpenGLES)
    sys.excepthook = except_hook
    ex = TDCS_GUI()
    ex.show()
    if len(args) > 1:
        if args[1].endswith(".mat"):
            ex.openSimnibsFile(args[1])
        elif args[1].endswith(".msh"):
            ex.loadHeadModel(args[1])
        else:
            raise IOError('simnibs_gui can only load .mat and .msh files')
    sys.exit(app.exec_()) 
Example #4
Source File: parallel.py    From pygrametl with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _getexcepthook():
    "Return a function that can be used as except hook for uncaught exceptions."
    if not sys.argv[0]:
        # We are in interactive mode and don't want to terminate
        return sys.excepthook
    # else create a function that terminates all spawned processes and this
    # in case of an uncaught exception
    exit = _getexitfunction()

    def excepthook(exctype, excvalue, exctraceback):
        import traceback
        sys.stderr.write(
            "An uncaught exception occured. Terminating pygrametl.\n")
        traceback.print_exception(exctype, excvalue, exctraceback)
        exit()
    return excepthook


# Stuff for @splitpoint 
Example #5
Source File: SConf.py    From arnold-usd with Apache License 2.0 6 votes vote down vote up
def failed(self):
        # check, if the reason was a ConfigureDryRunError or a
        # ConfigureCacheError and if yes, reraise the exception
        exc_type = self.exc_info()[0]
        if issubclass(exc_type, SConfError):
            raise
        elif issubclass(exc_type, SCons.Errors.BuildError):
            # we ignore Build Errors (occurs, when a test doesn't pass)
            # Clear the exception to prevent the contained traceback
            # to build a reference cycle.
            self.exc_clear()
        else:
            self.display('Caught exception while building "%s":\n' %
                         self.targets[0])
            sys.excepthook(*self.exc_info())
        return SCons.Taskmaster.Task.failed(self) 
Example #6
Source File: debug.py    From asynq with Apache License 2.0 6 votes vote down vote up
def attach_exception_hook():
    """Injects async exception hook into the sys.excepthook."""
    try:
        # detect whether we're running in IPython
        __IPYTHON__
    except NameError:
        shell = None
    else:
        # override ipython's exception handler if in a shell.
        # we need to do this because ipython overrides sys.excepthook
        # so just the else block doesn't cover that case.
        from IPython.core.getipython import get_ipython

        # this may be None if __IPYTHON__ is somehow defined, but we are not
        # in fact in a shell
        shell = get_ipython()

    if shell is not None:
        shell.set_custom_exc((BaseException,), ipython_custom_exception_handler)
    else:
        global is_attached, original_hook
        if is_attached:
            sys.stderr.write("Warning: async exception hook was already attached.\n")
            return
        original_hook = sys.excepthook
        sys.excepthook = async_exception_hook
        is_attached = True 
Example #7
Source File: didyoumean_api_tests.py    From DidYouMean-Python with MIT License 6 votes vote down vote up
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()
            with suppress_stderr():
                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 #8
Source File: cli.py    From Nest with MIT License 6 votes vote down vote up
def hook_exceptions(self, logger: logging.RootLogger) -> None:
        """Format excetion traceback.
        
        Parameters:
            logger:
                The logger for logging exceptions.
        """

        def _hook(exc_type, value, exc_tb) -> None:
            nest_dir = os.path.dirname(os.path.abspath(__file__))
            traceback_str = ''
            idx = 0
            for file_name, line_number, func_name, text in traceback.extract_tb(exc_tb)[1:]:
                # skip Nest-related tracebacks to make it more readable
                if os.path.dirname(os.path.abspath(file_name)) == nest_dir:
                    continue
                idx += 1
                traceback_str += '\n  [%d] File "%s", line %d, in function "%s"\n    %s' % \
                    (idx, file_name, line_number, func_name, text)
            if traceback_str != '':
                traceback_str = 'Traceback: ' + traceback_str
            logger.critical('Exception occurred during resolving:\nType: %s\nMessage: %s\n%s' % \
                (exc_type.__name__, value, traceback_str))

        sys.excepthook = _hook 
Example #9
Source File: SConf.py    From web2board with GNU Lesser General Public License v3.0 6 votes vote down vote up
def failed(self):
        # check, if the reason was a ConfigureDryRunError or a
        # ConfigureCacheError and if yes, reraise the exception
        exc_type = self.exc_info()[0]
        if issubclass(exc_type, SConfError):
            raise
        elif issubclass(exc_type, SCons.Errors.BuildError):
            # we ignore Build Errors (occurs, when a test doesn't pass)
            # Clear the exception to prevent the contained traceback
            # to build a reference cycle.
            self.exc_clear()
        else:
            self.display('Caught exception while building "%s":\n' %
                         self.targets[0])
            try:
                excepthook = sys.excepthook
            except AttributeError:
                # Earlier versions of Python don't have sys.excepthook...
                def excepthook(type, value, tb):
                    traceback.print_tb(tb)
                    print type, value
            excepthook(*self.exc_info())
        return SCons.Taskmaster.Task.failed(self) 
Example #10
Source File: parallelizer.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
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:
                try:
                    self.progressDlg.__exit__(None, None, None)
                except Exception:
                    pass 
Example #11
Source File: test___main__.py    From exopy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_running_main(exopy_qtbot, app_dir, monkeypatch):
    """Test starting the main app and closing it.

    """
    from enaml.workbench.ui.ui_plugin import UIPlugin

    def wait_for_window(self):
        pass

    # Do not release the application
    def no_release(self):
        pass

    monkeypatch.setattr(UIPlugin, '_release_application', no_release)
    monkeypatch.setattr(UIPlugin, 'start_application', wait_for_window)

    import sys
    old = sys.excepthook
    try:
        main([])
    finally:
        sys.excepthook = old 
Example #12
Source File: weakref.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _exitfunc(cls):
        # At shutdown invoke finalizers for which atexit is true.
        # This is called once all other non-daemonic threads have been
        # joined.
        reenable_gc = False
        try:
            if cls._registry:
                import gc
                if gc.isenabled():
                    reenable_gc = True
                    gc.disable()
                pending = None
                while True:
                    if pending is None or finalize._dirty:
                        pending = cls._select_for_exit()
                        finalize._dirty = False
                    if not pending:
                        break
                    f = pending.pop()
                    try:
                        # gc is disabled, so (assuming no daemonic
                        # threads) the following is the only line in
                        # this function which might trigger creation
                        # of a new finalizer
                        f()
                    except Exception:
                        sys.excepthook(*sys.exc_info())
                    assert f not in cls._registry
        finally:
            # prevent any more finalizers from executing during shutdown
            finalize._shutdown = True
            if reenable_gc:
                gc.enable() 
Example #13
Source File: plugin.py    From exopy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def install_excepthook(self):
        """Setup a global sys.excepthook for a nicer user experience.

        The error message suggest to the user to restart the app. In the future
        adding an automatic bug report system here would make sense.

        """
        def exception_handler(cls, value, traceback):
            """Log the error and signal to the user that it should restart the
            app.

            """
            msg = 'An uncaught exception occured :\n%s : %s\nTraceback:\n%s'
            logger.error(msg % (cls.__name__, value,
                         ''.join(format_tb(traceback))))

            ui = self.workbench.get_plugin('enaml.workbench.ui')
            msg = ('An uncaught exception occured. This should not happen '
                   'and can have a number of side effects. It is hence '
                   'advised to save your work and restart the application.')
            warning(ui.window, 'Consider restart', fill(msg))

        import sys
        sys.excepthook = exception_handler

    # =========================================================================
    # --- Private API ---------------------------------------------------------
    # =========================================================================

    #: Contributed error handlers. 
Example #14
Source File: logs.py    From clusterfuzz with Apache License 2.0 5 votes vote down vote up
def configure(name, extras=None):
  """Set logger. See the list of loggers in bot/config/logging.yaml.
  Also configures the process to log any uncaught exceptions as an error.
  |extras| will be included by emit() in log messages."""
  suppress_unwanted_warnings()

  if _is_running_on_app_engine():
    configure_appengine()
    return

  if _console_logging_enabled():
    logging.basicConfig()
  else:
    config.dictConfig(get_logging_config_dict(name))

  logger = logging.getLogger(name)
  logger.setLevel(logging.INFO)
  set_logger(logger)

  # Set _default_extras so they can be used later.
  if extras is None:
    extras = {}
  global _default_extras
  _default_extras = extras

  # Install an exception handler that will log an error when there is an
  # uncaught exception.
  sys.excepthook = uncaught_exception_handler 
Example #15
Source File: interactive_test.py    From pdir2 with MIT License 5 votes vote down vote up
def interactive_test():
    """
    This function runs pdir2 in bpython, ipython, ptpython.
    Note that giving the right output does not mean pdir2 works correctly,
    because print(string) is not equivalent to repr it in a REPL.
    To ensure everything truely works, manually verification is necessary.
    """
    print('Environment: ' + _get_repl_type().value)
    import requests

    print('\nShould show result of pdir(requests):')
    print(pdir(requests))
    # if any('bpython' in key for key in sys.modules):
    if _get_repl_type() == ReplType.BPYTHON:
        import sys

        # exit() in bpython interactive mode leads to a ValueError.
        # So I defined an exception hook to silent it.
        # sys.exit(0) is to make tox believe there's no error.
        def deal_with_exception_when_exit(a, b, c):
            sys.exit(0)

        sys.excepthook = deal_with_exception_when_exit
        exit()
    else:
        exit() 
Example #16
Source File: commbase.py    From spyder-kernels with MIT License 5 votes vote down vote up
def __repr__(self):
        """Get repr."""
        return repr(self.error)


# Replace sys.excepthook to handle CommsErrorWrapper 
Example #17
Source File: __main__.py    From exopy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup_thread_excepthook():
    """
    Workaround for `sys.excepthook` thread bug from:
    http://bugs.python.org/issue1230540

    Call once from the main thread before creating any threads.
    """

    init_original = threading.Thread.__init__

    def init(self, *args, **kwargs):
        """Modify the run method to use sys.excepthook.

        """
        init_original(self, *args, **kwargs)
        run_original = self.run

        def run_with_except_hook(*args2, **kwargs2):
            """Call sys.excepthook if any error occurs in the thread.

            """
            try:
                run_original(*args2, **kwargs2)
            except Exception:  # pragma: no cover
                sys.excepthook(*sys.exc_info())  # pragma: no cover

        self.run = run_with_except_hook

    threading.Thread.__init__ = init 
Example #18
Source File: application.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def do_shutdown(self):
		Gtk.Application.do_shutdown(self)
		sys.excepthook = sys.__excepthook__
		self.emit('config-save') 
Example #19
Source File: site.py    From meddle with MIT License 5 votes vote down vote up
def execusercustomize():
    """Run custom user specific code, if available."""
    try:
        import usercustomize
    except ImportError:
        pass
    except Exception:
        if sys.flags.verbose:
            sys.excepthook(*sys.exc_info())
        else:
            print>>sys.stderr, \
                "'import usercustomize' failed; use -v for traceback" 
Example #20
Source File: SpinBox.py    From tf-pose with Apache License 2.0 5 votes vote down vote up
def validate(self, strn, pos):
        if self.skipValidate:
            ret = QtGui.QValidator.Acceptable
        else:
            try:
                val = self.interpret()
                if val is False:
                    ret = QtGui.QValidator.Intermediate
                else:
                    if self.valueInRange(val):
                        if not self.opts['delayUntilEditFinished']:
                            self.setValue(val, update=False)
                        ret = QtGui.QValidator.Acceptable
                    else:
                        ret = QtGui.QValidator.Intermediate
                        
            except:
                import sys
                sys.excepthook(*sys.exc_info())
                ret = QtGui.QValidator.Intermediate
            
        ## draw / clear border
        if ret == QtGui.QValidator.Intermediate:
            self.textValid = False
        elif ret == QtGui.QValidator.Acceptable:
            self.textValid = True
        ## note: if text is invalid, we don't change the textValid flag 
        ## since the text will be forced to its previous state anyway
        self.update()
        
        self.errorBox.setVisible(not self.textValid)
        
        ## support 2 different pyqt APIs. Bleh.
        if hasattr(QtCore, 'QString'):
            return (ret, pos)
        else:
            return (ret, strn, pos) 
Example #21
Source File: site.py    From meddle with MIT License 5 votes vote down vote up
def execsitecustomize():
    """Run custom site specific code, if available."""
    try:
        import sitecustomize
    except ImportError:
        pass
    except Exception:
        if sys.flags.verbose:
            sys.excepthook(*sys.exc_info())
        else:
            print >>sys.stderr, \
                "'import sitecustomize' failed; use -v for traceback" 
Example #22
Source File: cgitb.py    From meddle with MIT License 5 votes vote down vote up
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 #23
Source File: util.py    From rl_graph_generation with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def install_mpi_excepthook():
    import sys
    from mpi4py import MPI
    old_hook = sys.excepthook

    def new_hook(a, b, c):
        old_hook(a, b, c)
        sys.stdout.flush()
        sys.stderr.flush()
        MPI.COMM_WORLD.Abort()
    sys.excepthook = new_hook 
Example #24
Source File: debug.py    From asynq with Apache License 2.0 5 votes vote down vote up
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 #25
Source File: setup.py    From tf-pose with Apache License 2.0 5 votes vote down vote up
def run(self):
        global path, version, initVersion, forcedVersion, installVersion
        
        name = self.config_vars['dist_name']
        path = os.path.join(self.install_libbase, 'pyqtgraph')
        if os.path.exists(path):
            raise Exception("It appears another version of %s is already "
                            "installed at %s; remove this before installing." 
                            % (name, path))
        print("Installing to %s" % path)
        rval = install.install.run(self)

        
        # If the version in __init__ is different from the automatically-generated
        # version string, then we will update __init__ in the install directory
        if initVersion == version:
            return rval
        
        try:
            initfile = os.path.join(path, '__init__.py')
            data = open(initfile, 'r').read()
            open(initfile, 'w').write(re.sub(r"__version__ = .*", "__version__ = '%s'" % version, data))
            installVersion = version
        except:
            sys.stderr.write("Warning: Error occurred while setting version string in build path. "
                             "Installation will use the original version string "
                             "%s instead.\n" % (initVersion)
                             )
            if forcedVersion:
                raise
            installVersion = initVersion
            sys.excepthook(*sys.exc_info())
    
        return rval 
Example #26
Source File: exceptionHandling.py    From tf-pose with Apache License 2.0 5 votes vote down vote up
def implements(self, interface=None):
        ## this just makes it easy for us to detect whether an ExceptionHook is already installed.
        if interface is None:
            return ['ExceptionHandler']
        else:
            return interface == 'ExceptionHandler'
    


## replace built-in excepthook only if this has not already been done 
Example #27
Source File: debug.py    From tf-pose with Apache License 2.0 5 votes vote down vote up
def printException(exctype, value, traceback):
    """Print an exception with its full traceback.
    
    Set `sys.excepthook = printException` to ensure that exceptions caught
    inside Qt signal handlers are printed with their full stack trace.
    """
    print(''.join(formatException(exctype, value, traceback, skip=1))) 
Example #28
Source File: test_stability.py    From tf-pose with Apache License 2.0 5 votes vote down vote up
def crashtest():
    global allWidgets
    try:
        gc.disable()
        actions = [
                createWidget,
                #setParent,
                forgetWidget,
                showWidget,
                processEvents,
                #raiseException,
                #addReference,
                ]

        thread = WorkThread()
        thread.start()

        while True:
            try:
                action = randItem(actions)
                action()
                print('[%d widgets alive, %d zombie]' % (len(allWidgets), len(allWidgets) - len(widgets)))
            except KeyboardInterrupt:
                print("Caught interrupt; send another to exit.")
                try:
                    for i in range(100):
                        QtTest.QTest.qWait(100)
                except KeyboardInterrupt:
                    thread.terminate()
                    break
            except:
                sys.excepthook(*sys.exc_info())
    finally:
        gc.enable() 
Example #29
Source File: SpinBox.py    From tf-pose with Apache License 2.0 5 votes vote down vote up
def interpret(self):
        """Return value of text or False if text is invalid."""
        strn = self.lineEdit().text()
        
        # tokenize into numerical value, si prefix, and suffix
        try:
            val, siprefix, suffix = fn.siParse(strn, self.opts['regex'], suffix=self.opts['suffix'])
        except Exception:
            return False
            
        # check suffix
        if suffix != self.opts['suffix'] or (suffix == '' and siprefix != ''):
            return False
           
        # generate value
        val = self.opts['evalFunc'](val)
        if self.opts['int']:
            val = int(fn.siApply(val, siprefix))
        else:
            try:
                val = fn.siApply(val, siprefix)
            except Exception:
                import sys
                sys.excepthook(*sys.exc_info())
                return False

        return val 
Example #30
Source File: cryptokiller.py    From hack4career with Apache License 2.0 5 votes vote down vote up
def excepthook(*args):
    sys.exit(1)

# Reference: http://stackoverflow.com/questions/19672352/how-to-run-python-script-with-elevated-privilege-on-windows