python类__excepthook__()的实例源码

console.py 文件源码 项目:transpyler 作者: Transpyler 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
logger.py 文件源码 项目:pony 作者: Eastwu5788 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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))
python.py 文件源码 项目:AlphaHooks 作者: AlphaHooks 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
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
ipython_custom_exc.py 文件源码 项目:trio 作者: python-trio 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def custom_excepthook(*args):
    print("custom running!")
    return sys.__excepthook__(*args)
custom_excepthook.py 文件源码 项目:trio 作者: python-trio 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def custom_excepthook(*args):
    print("custom running!")
    return sys.__excepthook__(*args)
exchange_errors.py 文件源码 项目:catalyst 作者: enigmampc 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
application.py 文件源码 项目:leetcode 作者: thomasyimgit 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
test_sys.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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"))
facade.py 文件源码 项目:landscape-client 作者: CanonicalLtd 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
__main__.py 文件源码 项目:jwalk 作者: jwplayer 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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()
util.py 文件源码 项目:pytypes 作者: Stewori 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
parallel_analysis_interface.py 文件源码 项目:yt 作者: yt-project 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
main.py 文件源码 项目:Enibar 作者: ENIB 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def excepthook(*args):
    sys.__excepthook__(*args)
    sys.exit(1)
basetest.py 文件源码 项目:Enibar 作者: ENIB 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def excepthook(type_, value, tb):
    QtWidgets.QApplication.quit()
    sys.__excepthook__(type_, value, tb)
    sys.exit(1)
dAbot.py 文件源码 项目:dAbot 作者: KishanBagaria 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def except_hook(type, value, traceback):
    sys.__excepthook__(type, value, traceback)
    input('Press any key to exit...\n')
tb.py 文件源码 项目:devpy 作者: sametmax 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
error_han.py 文件源码 项目:gpvdm 作者: roderickmackenzie 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
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
test_sys.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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"))
test_code_module.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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__
code.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号