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.

32 Examples 7

Example 1

Project: PokemonGo-Map
Source File: runserver.py
View license
def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    log.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

Example 2

Project: imapbackup
Source File: imapbackup.py
View license
def cli_exception(typ, value, traceback):
  """Handle CTRL-C by printing newline instead of ugly stack trace"""
  if not issubclass(typ, KeyboardInterrupt):
    sys.__excepthook__(typ, value, traceback)
  else:
    sys.stdout.write("\n")
    sys.stdout.flush()

Example 3

Project: recipy
Source File: log.py
View license
def log_exception(typ, value, traceback):
    if option_set('general', 'debug'):
        print("Logging exception %s" % value)
    exception = {'type': typ.__name__,
                 'message': str(value),
                 'traceback': ''.join(format_tb(traceback))}
    # Update object in DB
    db = open_or_create_db()
    db.update({"exception": exception}, eids=[RUN_ID])
    db.close()
    # Done logging, call default exception handler
    sys.__excepthook__(typ, value, traceback)

Example 4

Project: MacTimeLog
Source File: log_util.py
View license
def _excepthook(ex_cls, ex, tb):
    logger = logging.getLogger('mactimelog')

    logger.error('{0}: {1}\n{2}'.format(
            getattr(ex_cls, '__name__', ex_cls), ex,
            ''.join(traceback.format_tb(tb)).strip()))

    return sys.__excepthook__(ex_cls, ex, tb)

Example 5

Project: subscription-manager
Source File: rhsm_d.py
View license
def excepthook_base(exc_type, exc_value, exc_traceback):
    # something failed before we even got logging setup
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    if enable_debug:
        sys.__excepthook__(exc_type, exc_value, exc_traceback)

    # something fundamental failed... how quiet should we be?
    sys.exit(0)

Example 6

Project: teuthology
Source File: worker.py
View license
def install_except_hook():
    """
    Install an exception hook that first logs any uncaught exception, then
    raises it.
    """
    def log_exception(exc_type, exc_value, exc_traceback):
        if not issubclass(exc_type, KeyboardInterrupt):
            log.critical("Uncaught exception", exc_info=(exc_type, exc_value,
                                                         exc_traceback))
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
    sys.excepthook = log_exception

Example 7

Project: PoGoMap-GUI
Source File: runserver.py
View license
def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    log.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

Example 8

Project: fail2ban
Source File: helpers.py
View license
def excepthook(exctype, value, traceback):
	"""Except hook used to log unhandled exceptions to Fail2Ban log
	"""
	getLogger("fail2ban").critical(
		"Unhandled exception in Fail2Ban:", exc_info=True)
	return sys.__excepthook__(exctype, value, traceback)

Example 9

Project: ReadableWebProxy
Source File: logSetup.py
View license
def exceptHook(exc_type, exc_value, exc_traceback):
	if issubclass(exc_type, KeyboardInterrupt):
		sys.__excepthook__(exc_type, exc_value, exc_traceback)
		return
	mainLogger = logging.getLogger("Main")			# Main logger
	mainLogger.critical('Uncaught exception!')
	mainLogger.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

Example 10

Project: ZeroNet
Source File: DebugHook.py
View license
def handleErrorNotify(*args):
    if args[0].__name__ == "KeyboardInterrupt":
        shutdown()
    if args[0].__name__ != "Notify":
        logging.exception("Unhandled exception")
        sys.__excepthook__(*args)

Example 11

Project: KiWI
Source File: install.py
View license
def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    logger.critical('Unhandled exception', exc_info=(exc_type, exc_value, exc_traceback))

Example 12

Project: calibre
Source File: main_window.py
View license
    def __call__(self, type, value, tb):
        mw = self.wref()
        if mw is not None:
            mw.unhandled_exception(type, value, tb)
        else:
            sys.__excepthook__(type, value, tb)

Example 13

Project: calibre
Source File: main_window.py
View license
    def __call__(self, type, value, tb):
        mw = self.wref()
        if mw is not None:
            mw.unhandled_exception(type, value, tb)
        else:
            sys.__excepthook__(type, value, tb)

Example 14

Project: archivematica
Source File: archivematicaMCP.py
View license
def _except_hook_log_everything(exc_type, exc_value, exc_traceback):
    """
    Replacement for default exception handler that logs exceptions.
    """
    # Reference http://stackoverflow.com/a/16993115/2475775
    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
    sys.__excepthook__(exc_type, exc_value, exc_traceback)

Example 15

Project: archivematica
Source File: archivematicaMCP.py
View license
def _except_hook_log_everything(exc_type, exc_value, exc_traceback):
    """
    Replacement for default exception handler that logs exceptions.
    """
    # Reference http://stackoverflow.com/a/16993115/2475775
    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
    sys.__excepthook__(exc_type, exc_value, exc_traceback)

Example 16

Project: mapturner
Source File: __init__.py
View license
    def _install_exception_handler(self):
        """
        Installs a replacement for sys.excepthook, which handles pretty-printing uncaught exceptions.
        """
        def handler(t, value, traceback):
            if self.args.verbose:
                sys.__excepthook__(t, value, traceback)
            else:
                sys.stderr.write('%s\n' % unicode(value).encode('utf-8'))

        sys.excepthook = handler

Example 17

Project: mapturner
Source File: __init__.py
View license
    def _install_exception_handler(self):
        """
        Installs a replacement for sys.excepthook, which handles pretty-printing uncaught exceptions.
        """
        def handler(t, value, traceback):
            if self.args.verbose:
                sys.__excepthook__(t, value, traceback)
            else:
                sys.stderr.write('%s\n' % unicode(value).encode('utf-8'))

        sys.excepthook = handler

Example 18

Project: clan
Source File: __init__.py
View license
    def _install_exception_handler(self):
        """
        Installs a replacement for sys.excepthook, which handles pretty-printing uncaught exceptions.
        """
        def handler(t, value, traceback):
            if self.args.verbose:
                sys.__excepthook__(t, value, traceback)
            else:
                sys.stderr.write('%s\n' % unicode(value).encode('utf-8'))

        sys.excepthook = handler

Example 19

Project: invar
Source File: cli.py
View license
    def _install_exception_handler(self):
        """
        Installs a replacement for sys.excepthook, which handles pretty-printing uncaught exceptions.
        """
        def handler(t, value, traceback):
            if self.args.verbose:
                sys.__excepthook__(t, value, traceback)
            else:
                print value

        sys.excepthook = handler

Example 20

Project: headphones
Source File: logger.py
View license
def initHooks(global_exceptions=True, thread_exceptions=True, pass_original=True):
    """
    This method installs exception catching mechanisms. Any exception caught
    will pass through the exception hook, and will be logged to the logger as
    an error. Additionally, a traceback is provided.

    This is very useful for crashing threads and any other bugs, that may not
    be exposed when running as daemon.

    The default exception hook is still considered, if pass_original is True.
    """

    def excepthook(*exception_info):
        # We should always catch this to prevent loops!
        try:
            message = "".join(traceback.format_exception(*exception_info))
            logger.error("Uncaught exception: %s", message)
        except:
            pass

        # Original excepthook
        if pass_original:
            sys.__excepthook__(*exception_info)

    # Global exception hook
    if global_exceptions:
        sys.excepthook = excepthook

    # Thread exception hook
    if thread_exceptions:
        old_init = threading.Thread.__init__

        def new_init(self, *args, **kwargs):
            old_init(self, *args, **kwargs)
            old_run = self.run

            def new_run(*args, **kwargs):
                try:
                    old_run(*args, **kwargs)
                except (KeyboardInterrupt, SystemExit):
                    raise
                except:
                    excepthook(*sys.exc_info())

            self.run = new_run

        # Monkey patch the run() by monkey patching the __init__ method
        threading.Thread.__init__ = new_init

Example 21

Project: anaconda
Source File: anaconda.py
View license
        def _earlyExceptionHandler(ty, value, traceback):
            iutil.ipmi_report(constants.IPMI_FAILED)
            iutil.vtActivate(1)
            return sys.__excepthook__(ty, value, traceback)

Example 22

Project: scoop
Source File: _control.py
View license
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 23

Project: shenidam
Source File: qshenidam.py
View license
    def new_excepthook(type,value,traceback):
        application.exit(1)
        sys.__excepthook__(type,value,traceback)
        return

Example 24

Project: friture
Source File: exceptionhandler.py
View license
def fileexcepthook(exception_type, exception_value, traceback_object):
    # also call the standard exception handler to have prints on the console
    sys.__excepthook__(exception_type, exception_value, traceback_object)

    separator = '-' * 80
    log_dir = QtCore.QStandardPaths.standardLocations(QtCore.QStandardPaths.AppDataLocation)[0]
    logFile = os.path.join(log_dir, "friture.log")

    versionInfo="Friture " + friture.__versionXXXX__

    timeString = time.strftime("%Y-%m-%d, %H:%M:%S")

    tbinfofile = io.StringIO()
    traceback.print_tb(traceback_object, None, tbinfofile)
    tbinfofile.seek(0)
    tbinfo = tbinfofile.read()
    errmsg = '%s: \n%s' % (str(exception_type), str(exception_value))
    sections = [separator, timeString, separator, errmsg, separator, tbinfo, separator, versionInfo]
    msg = '\n'.join(sections)

    try:
        os.makedirs(log_dir, exist_ok=True)
        with open(logFile, "w") as f:
            f.write(msg)
    except IOError as e:
        print(e)
        pass

    notice = \
        """An unhandled exception occurred. Please report the problem\n"""\
        """on GitHub or via email to <%s>.\n"""\
        """A log has been written to "%s".\n\nError information:\n""" % \
        ("[email protected]", logFile)

    return str(notice)+str(msg)

Example 25

View license
def exception_hook(type, value, traceback):
    """
    Use sys.__excepthook__, the standard hook.
    """
    sys.__excepthook__(type, value, traceback)

Example 26

Project: pyqtggpo
Source File: util.py
View license
def loggerInit():
    debuglog = logging.getLogger('GGPODebug')
    debuglog.setLevel(logging.INFO)
    fh = logging.handlers.RotatingFileHandler(
        os.path.join(expanduser("~"), 'ggpodebug.log'), mode='a', maxBytes=500000, backupCount=10)
    if Settings.value(Settings.DEBUG_LOG):
        fh.setLevel(logging.INFO)
    else:
        fh.setLevel(logging.ERROR)
    ch = logging.StreamHandler()
    ch.setLevel(logging.ERROR)
    debuglog.addHandler(fh)
    debuglog.addHandler(ch)

    def handle_exception(exc_type, exc_value, exc_traceback):
        if issubclass(exc_type, KeyboardInterrupt):
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            return
        debuglog.error("<Uncaught exception>", exc_info=(exc_type, exc_value, exc_traceback))
    sys.excepthook = handle_exception

    if __name__ == "__main__":
        raise RuntimeError("Test unhandled")

    userlog = logging.getLogger('GGPOUser')
    userlog.setLevel(logging.INFO)
    fh = logging.handlers.RotatingFileHandler(
        os.path.join(expanduser("~"), 'ggpo.log'), mode='a', maxBytes=500000, backupCount=10)
    fh.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(message)s', "%Y-%m-%d %H:%M")
    fh.setFormatter(formatter)
    userlog.addHandler(fh)

Example 27

Project: plexpy
Source File: logger.py
View license
def initHooks(global_exceptions=True, thread_exceptions=True, pass_original=True):
    """
    This method installs exception catching mechanisms. Any exception caught
    will pass through the exception hook, and will be logged to the logger as
    an error. Additionally, a traceback is provided.

    This is very useful for crashing threads and any other bugs, that may not
    be exposed when running as daemon.

    The default exception hook is still considered, if pass_original is True.
    """

    def excepthook(*exception_info):
        # We should always catch this to prevent loops!
        try:
            message = "".join(traceback.format_exception(*exception_info))
            logger.error("Uncaught exception: %s", message)
        except:
            pass

        # Original excepthook
        if pass_original:
            sys.__excepthook__(*exception_info)

    # Global exception hook
    if global_exceptions:
        sys.excepthook = excepthook

    # Thread exception hook
    if thread_exceptions:
        old_init = threading.Thread.__init__

        def new_init(self, *args, **kwargs):
            old_init(self, *args, **kwargs)
            old_run = self.run

            def new_run(*args, **kwargs):
                try:
                    old_run(*args, **kwargs)
                except (KeyboardInterrupt, SystemExit):
                    raise
                except:
                    excepthook(*sys.exc_info())
            self.run = new_run

        # Monkey patch the run() by monkey patching the __init__ method
        threading.Thread.__init__ = new_init

Example 28

Project: plexpy
Source File: logger.py
View license
def initHooks(global_exceptions=True, thread_exceptions=True, pass_original=True):
    """
    This method installs exception catching mechanisms. Any exception caught
    will pass through the exception hook, and will be logged to the logger as
    an error. Additionally, a traceback is provided.

    This is very useful for crashing threads and any other bugs, that may not
    be exposed when running as daemon.

    The default exception hook is still considered, if pass_original is True.
    """

    def excepthook(*exception_info):
        # We should always catch this to prevent loops!
        try:
            message = "".join(traceback.format_exception(*exception_info))
            logger.error("Uncaught exception: %s", message)
        except:
            pass

        # Original excepthook
        if pass_original:
            sys.__excepthook__(*exception_info)

    # Global exception hook
    if global_exceptions:
        sys.excepthook = excepthook

    # Thread exception hook
    if thread_exceptions:
        old_init = threading.Thread.__init__

        def new_init(self, *args, **kwargs):
            old_init(self, *args, **kwargs)
            old_run = self.run

            def new_run(*args, **kwargs):
                try:
                    old_run(*args, **kwargs)
                except (KeyboardInterrupt, SystemExit):
                    raise
                except:
                    excepthook(*sys.exc_info())
            self.run = new_run

        # Monkey patch the run() by monkey patching the __init__ method
        threading.Thread.__init__ = new_init

Example 29

Project: Web2Executable
Source File: config.py
View license
def my_excepthook(type_, value, tback):
    output_err = ''.join([x for x in traceback.format_exception(type_, value, tback)])
    logger.error('{}'.format(output_err))
    sys.__excepthook__(type_, value, tback)

Example 30

Project: Web2Executable
Source File: config.py
View license
def my_excepthook(type_, value, tback):
    output_err = ''.join([x for x in traceback.format_exception(type_, value, tback)])
    logger.error('{}'.format(output_err))
    sys.__excepthook__(type_, value, tback)

Example 31

Project: FunKeyCIA
Source File: FunKeyCIA.py
View license
def exceptionhandler(exctype, value, traceback):
    if exctype == IndexError:
        parser.print_usage()
    else:
        sys.__excepthook__(exctype, value, traceback)

Example 32

Project: FunKeyCIA
Source File: FunKeyCIA.py
View license
def exceptionhandler(exctype, value, traceback):
    if exctype == IndexError:
        parser.print_usage()
    else:
        sys.__excepthook__(exctype, value, traceback)