Python sys.__excepthook__() Examples

The following are code examples for showing how to use sys.__excepthook__(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: iCount   Author: tomazc   File: logger.py    (license) View Source Project 7 votes vote down vote up
def _log_all_uncaught_exceptions(exc_type, exc_value, exc_traceback):
    """Log all uncaught exceptions in non-interactive mode.

    All python exceptions are handled by function, stored in
    ``sys.excepthook.`` By rewriting the default implementation, we
    can modify handling of all uncaught exceptions.

    Warning: modified behaviour (logging of all uncaught exceptions)
    applies only when runing in non-interactive mode.

    """
    # ignore KeyboardInterrupt
    if not issubclass(exc_type, KeyboardInterrupt):
        ROOT_LOGGER.error("", exc_info=(exc_type, exc_value, exc_traceback))

    sys.__excepthook__(exc_type, exc_value, exc_traceback)
    return


# Rewrite the default implementation os sys.excepthook to log all
# uncaught exceptions: 
Example 2
Project: janna   Author: jhlee525   File: logger.py    (license) View Source Project 6 votes vote down vote up
def _exception_hook(exc_type, exc_value, exc_traceback):
    if exc_type.__name__ == 'StreamerError':
        node = exc_value.node
        error = exc_value.error
        # node.graph.draw(attention=node)
        logger.error('Error occured when running streamers. See graph')
        exc_type = type(error)
        exc_value = error
    elif exc_type.__name__ == 'StreamerConnError':
        node1 = exc_value.src_node
        node2 = exc_value.tgt_node
        error = exc_value.error
        # node1.graph.draw(attention=[node1, node2])
        logger.error('Error occured when running streamers. See graph')
        exc_type = type(error)
        exc_value = error
    sys.__excepthook__(exc_type, exc_value, exc_traceback) 
Example 3
Project: octario   Author: redhat-openstack   File: logger.py    (license) View Source Project 6 votes vote down vote up
def octario_excepthook(exc_type, exc_value, exc_traceback):
    """exception hook that sends OctarioException to log and other

    exceptions to stderr (default excepthook)
    """
    from octario.lib.exceptions import OctarioException

    # sends full exception with trace to log
    if not isinstance(exc_value, OctarioException):
        return sys.__excepthook__(exc_type, exc_value, exc_traceback)

    if LOG.getEffectiveLevel() <= logging.DEBUG:
        formated_exception = "".join(
            traceback.format_exception(exc_type, exc_value, exc_traceback))
        LOG.error(formated_exception + exc_value.message)
    else:
        LOG.error(exc_value.message) 
Example 4
Project: cuny-bdif   Author: aristotle-tek   File: awsqueryrequest.py    (license) View Source Project 6 votes vote down vote up
def boto_except_hook(debugger_flag, debug_flag):
    def excepthook(typ, value, tb):
        if typ is bdb.BdbQuit:
            sys.exit(1)
        sys.excepthook = sys.__excepthook__

        if debugger_flag and sys.stdout.isatty() and sys.stdin.isatty():
            if debugger.__name__ == 'epdb':
                debugger.post_mortem(tb, typ, value)
            else:
                debugger.post_mortem(tb)
        elif debug_flag:
            print(traceback.print_tb(tb))
            sys.exit(1)
        else:
            print(value)
            sys.exit(1)

    return excepthook 
Example 5
Project: rcli   Author: contains-io   File: dispatcher.py    (license) View Source Project 6 votes vote down vote up
def main():
    # type: () -> typing.Any
    """Parse the command line options and launch the requested command.

    If the command is 'help' then print the help message for the subcommand; if
    no subcommand is given, print the standard help message.
    """
    colorama.init(wrap=six.PY3)
    doc = usage.get_primary_command_usage()
    allow_subcommands = '<command>' in doc
    args = docopt(doc, version=settings.version,
                  options_first=allow_subcommands)
    if sys.excepthook is sys.__excepthook__:
        sys.excepthook = log.excepthook
    try:
        log.enable_logging(log.get_log_level(args))
        default_args = sys.argv[2 if args.get('<command>') else 1:]
        if (args.get('<command>') == 'help' and
                None not in settings.subcommands):
            subcommand = next(iter(args.get('<args>', default_args)), None)
            return usage.get_help_usage(subcommand)
        argv = [args.get('<command>')] + args.get('<args>', default_args)
        return _run_command(argv)
    except exc.InvalidCliValueError as e:
        return str(e) 
Example 6
Project: yt   Author: yt-project   File: funcs.py    (license) View Source Project 6 votes vote down vote up
def paste_traceback(exc_type, exc, tb):
    """
    This is a traceback handler that knows how to paste to the pastebin.
    Should only be used in sys.excepthook.
    """
    sys.__excepthook__(exc_type, exc, tb)
    from yt.extern.six.moves import StringIO, xmlrpc_client
    p = xmlrpc_client.ServerProxy(
            "http://paste.yt-project.org/xmlrpc/",
            allow_none=True)
    s = StringIO()
    traceback.print_exception(exc_type, exc, tb, file=s)
    s = s.getvalue()
    ret = p.pastes.newPaste('pytb', s, None, '', '', True)
    print()
    print("Traceback pasted to http://paste.yt-project.org/show/%s" % (ret))
    print() 
Example 7
Project: oil   Author: oilshell   File: test_exceptions.py    (license) View Source Project 6 votes vote down vote up
def test_unhandled(self):
        # Check for sensible reporting of unhandled exceptions
        for exc_type in (ValueError, BrokenStrException):
            try:
                exc = exc_type("test message")
                # The following line is included in the traceback report:
                raise exc
            except exc_type:
                with captured_stderr() as stderr:
                    sys.__excepthook__(*sys.exc_info())
            report = stderr.getvalue()
            self.assertIn("test_exceptions.py", report)
            self.assertIn("raise exc", report)
            self.assertIn(exc_type.__name__, report)
            if exc_type is BrokenStrException:
                self.assertIn("<exception str() failed>", report)
            else:
                self.assertIn("test message", report)
            self.assertTrue(report.endswith("\n")) 
Example 8
Project: oil   Author: oilshell   File: test_sys.py    (license) View Source Project 6 votes vote down vote up
def test_original_excepthook(self):
        savestderr = sys.stderr
        err = cStringIO.StringIO()
        sys.stderr = err

        eh = sys.__excepthook__

        self.assertRaises(TypeError, eh)
        try:
            raise ValueError(42)
        except ValueError, exc:
            eh(*sys.exc_info())

        sys.stderr = savestderr
        self.assertTrue(err.getvalue().endswith("ValueError: 42\n"))

    # FIXME: testing the code for a lost or replaced excepthook in
    # Python/pythonrun.c::PyErr_PrintEx() is tricky. 
Example 9
Project: python2-tracer   Author: extremecoders-re   File: test_exceptions.py    (license) View Source Project 6 votes vote down vote up
def test_unhandled(self):
        # Check for sensible reporting of unhandled exceptions
        for exc_type in (ValueError, BrokenStrException):
            try:
                exc = exc_type("test message")
                # The following line is included in the traceback report:
                raise exc
            except exc_type:
                with captured_stderr() as stderr:
                    sys.__excepthook__(*sys.exc_info())
            report = stderr.getvalue()
            self.assertIn("test_exceptions.py", report)
            self.assertIn("raise exc", report)
            self.assertIn(exc_type.__name__, report)
            if exc_type is BrokenStrException:
                self.assertIn("<exception str() failed>", report)
            else:
                self.assertIn("test message", report)
            self.assertTrue(report.endswith("\n")) 
Example 10
Project: python2-tracer   Author: extremecoders-re   File: test_sys.py    (license) View Source Project 6 votes vote down vote up
def test_original_excepthook(self):
        savestderr = sys.stderr
        err = cStringIO.StringIO()
        sys.stderr = err

        eh = sys.__excepthook__

        self.assertRaises(TypeError, eh)
        try:
            raise ValueError(42)
        except ValueError, exc:
            eh(*sys.exc_info())

        sys.stderr = savestderr
        self.assertTrue(err.getvalue().endswith("ValueError: 42\n"))

    # FIXME: testing the code for a lost or replaced excepthook in
    # Python/pythonrun.c::PyErr_PrintEx() is tricky. 
Example 11
Project: borgcube   Author: enkore   File: server.py    (license) View Source Project 6 votes vote down vote up
def exit_by_exception():
    class SignalException(BaseException):
        pass

    def signal_fork(signum, stack_frame):
        log.info('Received signal %d, procuring hariki', signum)
        raise SignalException(signum)

    def excepthook(exc_type, exc_value, exc_trace):
        if exc_type is SignalException:
            sys.exit(1)
        else:
            sys.__excepthook__(exc_type, exc_value, exc_trace)

    sys.excepthook = excepthook
    signal.signal(signal.SIGINT, signal_fork)
    signal.signal(signal.SIGTERM, signal_fork) 
Example 12
Project: learneveryword   Author: karan   File: awsqueryrequest.py    (license) View Source Project 6 votes vote down vote up
def boto_except_hook(debugger_flag, debug_flag):
    def excepthook(typ, value, tb):
        if typ is bdb.BdbQuit:
            sys.exit(1)
        sys.excepthook = sys.__excepthook__

        if debugger_flag and sys.stdout.isatty() and sys.stdin.isatty():
            if debugger.__name__ == 'epdb':
                debugger.post_mortem(tb, typ, value)
            else:
                debugger.post_mortem(tb)
        elif debug_flag:
            print(traceback.print_tb(tb))
            sys.exit(1)
        else:
            print(value)
            sys.exit(1)

    return excepthook 
Example 13
Project: e2end   Author: oplatek   File: debug.py    (license) View Source Project 6 votes vote down vote up
def exc_info_hook(exc_type, value, tb):
    """An exception hook that starts IPdb automatically on error if in interactive mode."""

    if hasattr(sys, 'ps1') or not sys.stderr.isatty() or exc_type == KeyboardInterrupt:
        # we are in interactive mode, we don't have a tty-like
        # device,, or the user triggered a KeyboardInterrupt,
        # so we call the default hook
        sys.__excepthook__(exc_type, value, tb)
    else:
        import traceback
        import ipdb
        # we are NOT in interactive mode, print the exception
        traceback.print_exception(exc_type, value, tb)
        # then start the debugger in post-mortem mode.
        # pdb.pm() # deprecated
        ipdb.post_mortem(tb)  # more modern 
Example 14
Project: pefile.pypy   Author: cloudtracer   File: test_sys.py    (license) View Source Project 6 votes vote down vote up
def test_original_excepthook(self):
        savestderr = sys.stderr
        err = cStringIO.StringIO()
        sys.stderr = err

        eh = sys.__excepthook__

        self.assertRaises(TypeError, eh)
        try:
            raise ValueError(42)
        except ValueError, exc:
            eh(*sys.exc_info())

        sys.stderr = savestderr
        self.assertTrue(err.getvalue().endswith("ValueError: 42\n"))

    # FIXME: testing the code for a lost or replaced excepthook in
    # Python/pythonrun.c::PyErr_PrintEx() is tricky. 
Example 15
Project: ndk-python   Author: gittor   File: test_sys.py    (license) View Source Project 6 votes vote down vote up
def test_original_excepthook(self):
        savestderr = sys.stderr
        err = cStringIO.StringIO()
        sys.stderr = err

        eh = sys.__excepthook__

        self.assertRaises(TypeError, eh)
        try:
            raise ValueError(42)
        except ValueError, exc:
            eh(*sys.exc_info())

        sys.stderr = savestderr
        self.assertTrue(err.getvalue().endswith("ValueError: 42\n"))

    # FIXME: testing the code for a lost or replaced excepthook in
    # Python/pythonrun.c::PyErr_PrintEx() is tricky. 
Example 16
Project: Chromium_DepotTools   Author: p07r0457   File: awsqueryrequest.py    (license) View Source Project 6 votes vote down vote up
def boto_except_hook(debugger_flag, debug_flag):
    def excepthook(typ, value, tb):
        if typ is bdb.BdbQuit:
            sys.exit(1)
        sys.excepthook = sys.__excepthook__

        if debugger_flag and sys.stdout.isatty() and sys.stdin.isatty():
            if debugger.__name__ == 'epdb':
                debugger.post_mortem(tb, typ, value)
            else:
                debugger.post_mortem(tb)
        elif debug_flag:
            print traceback.print_tb(tb)
            sys.exit(1)
        else:
            print value
            sys.exit(1)

    return excepthook 
Example 17
Project: node-gn   Author: Shouqun   File: awsqueryrequest.py    (license) View Source Project 6 votes vote down vote up
def boto_except_hook(debugger_flag, debug_flag):
    def excepthook(typ, value, tb):
        if typ is bdb.BdbQuit:
            sys.exit(1)
        sys.excepthook = sys.__excepthook__

        if debugger_flag and sys.stdout.isatty() and sys.stdin.isatty():
            if debugger.__name__ == 'epdb':
                debugger.post_mortem(tb, typ, value)
            else:
                debugger.post_mortem(tb)
        elif debug_flag:
            print traceback.print_tb(tb)
            sys.exit(1)
        else:
            print value
            sys.exit(1)

    return excepthook 
Example 18
Project: sysl   Author: anz-bank   File: debug.py    (license) View Source Project 6 votes vote down vote up
def _hook(type_, value, tback):
    """Exception hook callback."""
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like
        # device, so we call the default hook
        sys.__excepthook__(type_, value, tback)
    else:
        import traceback
        import pdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type_, value, tback)

        # Dirty hack because Py27 doesn't chain exceptions
        if value.args:
            tb2 = value.args[-1]
            if isinstance(tb2, type(tback)):
                ex = value.args[-2]
                print >>sys.stderr, '{}Caused by{} '.format(
                    ansi('1;35m'), ansi('0m')),
                traceback.print_exception(type_(ex), ex, tb2)

            print
        # ...then start the debugger in post-mortem mode.
        # pdb.pm() # deprecated
        pdb.post_mortem(tback)  # more "modern" 
Example 19
Project: resolwe-bio-py   Author: genialis   File: resdk_logger.py    (license) View Source Project 6 votes vote down vote up
def _log_all_uncaught_exceptions(exc_type, exc_value, exc_traceback):
    """Log all uncaught exceptions in non-interactive mode.

    All python exceptions are handled by function, stored in
    ``sys.excepthook.`` By rewriting the default implementation, we
    can modify handling of all uncaught exceptions.

    Warning: modified behaviour (logging of all uncaught exceptions)
    applies only when runing in non-interactive mode.

    """
    # ignore KeyboardInterrupt
    if not issubclass(exc_type, KeyboardInterrupt):
        ROOT_LOGGER.error("", exc_info=(exc_type, exc_value, exc_traceback))

    sys.__excepthook__(exc_type, exc_value, exc_traceback)
    return


# Rewrite the default implementation os sys.excepthook to log all
# uncaught exceptions: 
Example 20
Project: alfred-ec2   Author: SoMuchToGrok   File: awsqueryrequest.py    (license) View Source Project 6 votes vote down vote up
def boto_except_hook(debugger_flag, debug_flag):
    def excepthook(typ, value, tb):
        if typ is bdb.BdbQuit:
            sys.exit(1)
        sys.excepthook = sys.__excepthook__

        if debugger_flag and sys.stdout.isatty() and sys.stdin.isatty():
            if debugger.__name__ == 'epdb':
                debugger.post_mortem(tb, typ, value)
            else:
                debugger.post_mortem(tb)
        elif debug_flag:
            print(traceback.print_tb(tb))
            sys.exit(1)
        else:
            print(value)
            sys.exit(1)

    return excepthook 
Example 21
Project: kbe_server   Author: xiaohaoppy   File: xlsxError.py    (license) View Source Project 6 votes vote down vote up
def except_hook(typ, val, tb):
	"""
	traceback,?:?
	"""
	pywinerr_list = []
	sys.__excepthook__(typ, val, tb)
	ex = "\n"

	for e in traceback.format_exception(typ, val, tb):
		ex += e

	pywinerr_pos = ex.find('com_error')

	if pywinerr_pos > -1:
		error_str =  ex[pywinerr_pos+len('com_error')+1:].strip()
		xt.str2List(error_str[1:-1], pywinerr_list)
	return False
	#xt.inputList(pywinerr_list) 
Example 22
Project: infrared   Author: redhat-openstack   File: logger.py    (license) View Source Project 6 votes vote down vote up
def ir_excepthook(exc_type, exc_value, exc_traceback):
    """
    exception hook that sends IRException to log and other exceptions to
    stderr (default excepthook)
    """

    # sends full exception with trace to log
    if not isinstance(exc_value, exceptions.IRException):
        return sys.__excepthook__(exc_type, exc_value, exc_traceback)

    if LOG.getEffectiveLevel() <= logging.DEBUG:
        formated_exception = "".join(
            traceback.format_exception(exc_type, exc_value, exc_traceback))
        LOG.error(formated_exception + exc_value.message)
    else:
        LOG.error(exc_value.message) 
Example 23
Project: depot_tools   Author: webrtc-uwp   File: awsqueryrequest.py    (license) View Source Project 6 votes vote down vote up
def boto_except_hook(debugger_flag, debug_flag):
    def excepthook(typ, value, tb):
        if typ is bdb.BdbQuit:
            sys.exit(1)
        sys.excepthook = sys.__excepthook__

        if debugger_flag and sys.stdout.isatty() and sys.stdin.isatty():
            if debugger.__name__ == 'epdb':
                debugger.post_mortem(tb, typ, value)
            else:
                debugger.post_mortem(tb)
        elif debug_flag:
            print traceback.print_tb(tb)
            sys.exit(1)
        else:
            print value
            sys.exit(1)

    return excepthook 
Example 24
Project: Osdag   Author: osdag-admin   File: osdagMainPage.py    (license) View Source Project 6 votes vote down vote up
def the_exception_hook(exctype, value, traceback):
        '''Finds the error occurs when Osdag crashes

        Args:
            exctype: type of error
            value: information of the error
            traceback: trace the object

        Returns:
            system exit(1)
        '''
        # Print the error and traceback
        print "Error occurred: ", (exctype, value, traceback)
        # Call the normal Exception hook after
        sys.__excepthook__(exctype, value, traceback)
        sys.exit(1)

    # Set the exception hook to our wrapping function 
Example 25
Project: PyJFuzz   Author: mseclab   File: pjf_logger.py    (MIT License) View Source Project 5 votes vote down vote up
def init_logger():
        logging.basicConfig(filename="pjf_{0}.log".format(time.strftime("%d_%m_%Y")), level=PYJFUZZ_LOGLEVEL)
        logger = logging.getLogger(__name__)
        sys.tracebacklimit = 10

        def handle_exception(exc_type, exc_value, exc_traceback):
            if issubclass(exc_type, KeyboardInterrupt):
                sys.__excepthook__(exc_type, exc_value, exc_traceback)
                return
            logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
            sys.__excepthook__(exc_type, exc_value, None)
            return

        sys.excepthook = handle_exception
        return logger 
Example 26
Project: Harmonbot   Author: Harmon758   File: logging.py    (license) View Source Project 5 votes vote down vote up
def log_exception(exc_type, exc_value, exc_traceback):
	sys.__excepthook__(exc_type, exc_value, exc_traceback)
	errors_logger.error("Uncaught exception\n", exc_info = (exc_type, exc_value, exc_traceback)) 
Example 27
Project: PrivacyScore   Author: PrivacyScore   File: openwpm_wrapper.py    (license) View Source Project 5 votes vote down vote up
def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback)) 
Example 28
Project: zeronet-debian   Author: bashrc   File: DebugHook.py    (license) View Source Project 5 votes vote down vote up
def handleError(*args):
    global last_error
    if not args:  # Manual called
        args = sys.exc_info()
        silent = True
    else:
        silent = False
    if args[0].__name__ != "Notify":
        last_error = args
    if not silent and args[0].__name__ != "Notify":
        logging.exception("Unhandled exception")
        sys.__excepthook__(*args)


# Ignore notify errors 
Example 29
Project: zeronet-debian   Author: bashrc   File: DebugHook.py    (license) View Source Project 5 votes vote down vote up
def handleErrorNotify(*args):
    if args[0].__name__ != "Notify":
        logging.exception("Unhandled exception")
        sys.__excepthook__(*args) 
Example 30
Project: transpyler   Author: Transpyler   File: console.py    (license) View Source Project 5 votes vote down vote up
def showsyntaxerror(self, filename=None):
        type, value, tb = sys.exc_info()
        sys.last_type = type
        sys.last_value = value
        sys.last_traceback = tb

        if filename and type is SyntaxError:
            # Work hard to stuff the correct filename in the exception
            try:
                msg, (dummy_filename, lineno, offset, dummy_line) = value.args
            except ValueError:
                # Not the format we expect; leave it alone
                pass
            else:
                # Stuff in the right filename and line
                print(self.buffer, lineno)
                line = dummy_line
                value = SyntaxError(msg, (filename, lineno, offset, line))
                sys.last_value = value
        if sys.excepthook is sys.__excepthook__:
            lines = traceback.format_exception_only(type, value)
            self.write(''.join(lines))
        else:
            # If someone has set sys.excepthook, we let that take precedence
            # over self.write
            sys.excepthook(type, value, tb) 
Example 31
Project: pony   Author: Eastwu5788   File: logger.py    (license) View Source Project 5 votes vote down vote up
def add_error_log(code, messages):
    structure = {
        "code": code,
        "message": messages
    }
    user_logger.error(json.dumps(structure, cls=DateEncoder))


# ????????log
# _crash_logger = logging.getLogger("crash")
# ???log???
# _crash_handler = logging.FileHandler("/data/wwwlogs/crash_error.log")
# ??????????
# _crash_handler.setFormatter(logging.Formatter("%(message)s"))
# ?logger?????
# _crash_logger.addHandler(_crash_handler)
# ??????
# _crash_logger.setLevel(logging.ERROR)


# def uncaught_exception_handler(exc_type, exc_value, exc_traceback):
#     print("????")
#     if issubclass(exc_type, KeyboardInterrupt):
#         sys.__excepthook__(exc_type, exc_value, exc_traceback)
#         return
#     print("????")
#     _crash_logger.error("Uncaught exception", esc_info=(exc_type, exc_value, exc_traceback)) 
Example 32
Project: AlphaHooks   Author: AlphaHooks   File: python.py    (license) View Source Project 5 votes vote down vote up
def runcode(self, code):
        """
        Overrides and captures stdout and stdin from
        InteractiveConsole.
        """
        sys.stdout = self.stream
        sys.stderr = self.stream
        sys.excepthook = sys.__excepthook__
        self.running.emit(True)
        result = InteractiveConsole.runcode(self, code)
        self.running.emit(False)
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
        return result 
Example 33
Project: trio   Author: python-trio   File: ipython_custom_exc.py    (license) View Source Project 5 votes vote down vote up
def custom_excepthook(*args):
    print("custom running!")
    return sys.__excepthook__(*args) 
Example 34
Project: trio   Author: python-trio   File: custom_excepthook.py    (license) View Source Project 5 votes vote down vote up
def custom_excepthook(*args):
    print("custom running!")
    return sys.__excepthook__(*args) 
Example 35
Project: catalyst   Author: enigmampc   File: exchange_errors.py    (license) View Source Project 5 votes vote down vote up
def silent_except_hook(exctype, excvalue, exctraceback):
    if exctype in [PricingDataBeforeTradingError, PricingDataNotLoadedError,
                   SymbolNotFoundOnExchange, NoDataAvailableOnExchange,
                   ExchangeAuthEmpty]:
        fn = traceback.extract_tb(exctraceback)[-1][0]
        ln = traceback.extract_tb(exctraceback)[-1][1]
        print("Error traceback: {1} (line {2})\n"
              "{0.__name__}:  {3}".format(exctype, fn, ln, excvalue))
    else:
        sys.__excepthook__(exctype, excvalue, exctraceback) 
Example 36
Project: leetcode   Author: thomasyimgit   File: application.py    (license) View Source Project 5 votes vote down vote up
def init_crash_handler(self):
        """Create a crash handler, typically setting sys.excepthook to it."""
        self.crash_handler = self.crash_handler_class(self)
        sys.excepthook = self.excepthook
        def unset_crashhandler():
            sys.excepthook = sys.__excepthook__
        atexit.register(unset_crashhandler) 
Example 37
Project: zippy   Author: securesystemslab   File: test_sys.py    (license) View Source Project 5 votes vote down vote up
def test_original_excepthook(self):
        err = io.StringIO()
        sys.stderr = err

        eh = sys.__excepthook__

        self.assertRaises(TypeError, eh)
        try:
            raise ValueError(42)
        except ValueError as exc:
            eh(*sys.exc_info())

        self.assertTrue(err.getvalue().endswith("ValueError: 42\n")) 
Example 38
Project: landscape-client   Author: CanonicalLtd   File: facade.py    (license) View Source Project 5 votes vote down vote up
def _prevent_dpkg_apport_error(self, exc_type, exc_obj, exc_tb):
        """Prevent dpkg errors from generating Apport crash reports.

        When dpkg reports an error, a SystemError is raised and cleaned
        up in C code. However, it seems like the Apport except hook is
        called before the C code clears the error, generating crash
        reports even though nothing crashed.

        This exception hook doesn't call the Apport hook for
        SystemErrors, but it calls it for all other errors.
        """
        if exc_type is SystemError:
            sys.__excepthook__(exc_type, exc_obj, exc_tb)
            return
        self.old_excepthook(exc_type, exc_obj, exc_tb) 
Example 39
Project: jwalk   Author: jwplayer   File: __main__.py    (license) View Source Project 5 votes vote down vote up
def debug_hook(type_, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        sys.__excepthook__(type_, value, tb)
    else:
        import traceback
        import pdb
        traceback.print_exception(type_, value, tb)
        print(u"\n")
        pdb.pm() 
Example 40
Project: pytypes   Author: Stewori   File: util.py    (license) View Source Project 5 votes vote down vote up
def _pytypes_excepthook(exctype, value, tb):
    """"An excepthook suitable for use as sys.excepthook, that strips away
    the part of the traceback belonging to pytypes' internals.
    Can be switched on and off via pytypes.clean_traceback
    or pytypes.set_clean_traceback.
    The latter automatically installs this hook in sys.excepthook.
    """
    if pytypes.clean_traceback and issubclass(exctype, TypeError):
        traceback.print_exception(exctype, value, tb, _calc_traceback_limit(tb))
    else:
        if _sys_excepthook is None:
            sys.__excepthook__(exctype, value, tb)
        else:
            _sys_excepthook(exctype, value, tb) 
Example 41
Project: yt   Author: yt-project   File: parallel_analysis_interface.py    (license) View Source Project 5 votes vote down vote up
def traceback_writer_hook(file_suffix=""):
    def write_to_file(exc_type, exc, tb):
        sys.__excepthook__(exc_type, exc, tb)
        fn = "yt_traceback%s" % file_suffix
        with open(fn, "w") as fhandle:
            traceback.print_exception(exc_type, exc, tb, file=fhandle)
            print("Wrote traceback to %s" % fn)
        MPI.COMM_WORLD.Abort(1)
    return write_to_file 
Example 42
Project: Enibar   Author: ENIB   File: main.py    (license) View Source Project 5 votes vote down vote up
def excepthook(*args):
    sys.__excepthook__(*args)
    sys.exit(1) 
Example 43
Project: Enibar   Author: ENIB   File: basetest.py    (license) View Source Project 5 votes vote down vote up
def excepthook(type_, value, tb):
    QtWidgets.QApplication.quit()
    sys.__excepthook__(type_, value, tb)
    sys.exit(1) 
Example 44
Project: dAbot   Author: KishanBagaria   File: dAbot.py    (license) View Source Project 5 votes vote down vote up
def except_hook(type, value, traceback):
    sys.__excepthook__(type, value, traceback)
    input('Press any key to exit...\n') 
Example 45
Project: devpy   Author: sametmax   File: tb.py    (license) View Source Project 5 votes vote down vote up
def color_traceback(previous_hook=None):
    previous_hook = sys.excepthook

    def on_crash(type, value, tb):
        if getattr(sys.stderr, 'isatty'):
            colorizer = CustomColorizer('default')
            colorizer.colorize_traceback(type, value, tb)
            if previous_hook is not sys.__excepthook__:
                previous_hook(type, value, tb)

    sys.excepthook = on_crash 
Example 46
Project: gpvdm   Author: roderickmackenzie   File: error_han.py    (license) View Source Project 5 votes vote down vote up
def error_han(type, value, tback):
	if enable_betafeatures()==False:
		#formatted_lines = traceback.format_exc().splitlines()
		long_trace=traceback.format_exception(type, value, tback)
		long_trace=str("<br>".join(long_trace))
		trace=long_trace.replace("<br>","")
		trace=trace.replace(" ","")
		dialog=widget_error_han(long_trace,trace)
		dialog.exec_()
	sys.__excepthook__(type, value, tback)		
	return True 
Example 47
Project: web_ctp   Author: molebot   File: test_sys.py    (license) View Source Project 5 votes vote down vote up
def test_original_excepthook(self):
        err = io.StringIO()
        sys.stderr = err

        eh = sys.__excepthook__

        self.assertRaises(TypeError, eh)
        try:
            raise ValueError(42)
        except ValueError as exc:
            eh(*sys.exc_info())

        self.assertTrue(err.getvalue().endswith("ValueError: 42\n")) 
Example 48
Project: web_ctp   Author: molebot   File: test_code_module.py    (license) View Source Project 5 votes vote down vote up
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 49
Project: web_ctp   Author: molebot   File: code.py    (license) View Source Project 5 votes vote down vote up
def showsyntaxerror(self, filename=None):
        """Display the syntax error that just occurred.

        This doesn't display a stack trace because there isn't one.

        If a filename is given, it is stuffed in the exception instead
        of what was there before (because Python's parser always uses
        "<string>" when reading from a string).

        The output is written by self.write(), below.

        """
        type, value, tb = sys.exc_info()
        sys.last_type = type
        sys.last_value = value
        sys.last_traceback = tb
        if filename and type is SyntaxError:
            # Work hard to stuff the correct filename in the exception
            try:
                msg, (dummy_filename, lineno, offset, line) = value.args
            except ValueError:
                # Not the format we expect; leave it alone
                pass
            else:
                # Stuff in the right filename
                value = SyntaxError(msg, (filename, lineno, offset, line))
                sys.last_value = value
        if sys.excepthook is sys.__excepthook__:
            lines = traceback.format_exception_only(type, value)
            self.write(''.join(lines))
        else:
            # If someone has set sys.excepthook, we let that take precedence
            # over self.write
            sys.excepthook(type, value, tb) 
Example 50
Project: web_ctp   Author: molebot   File: code.py    (license) View Source Project 5 votes vote down vote up
def showtraceback(self):
        """Display the exception that just occurred.

        We remove the first stack item because it is our own code.

        The output is written by self.write(), below.

        """
        try:
            type, value, tb = sys.exc_info()
            sys.last_type = type
            sys.last_value = value
            sys.last_traceback = tb
            tblist = traceback.extract_tb(tb)
            del tblist[:1]
            lines = traceback.format_list(tblist)
            if lines:
                lines.insert(0, "Traceback (most recent call last):\n")
            lines.extend(traceback.format_exception_only(type, value))
        finally:
            tblist = tb = None
        if sys.excepthook is sys.__excepthook__:
            self.write(''.join(lines))
        else:
            # If someone has set sys.excepthook, we let that take precedence
            # over self.write
            sys.excepthook(type, value, tb)