cannot override sys.excepthook

前端 未结 4 841
星月不相逢
星月不相逢 2020-12-02 00:02

I try to customize behavior of sys.excepthook as described by the recipe.

in ipython:

:import pdb, sys, traceback
:def info(type, value         


        
相关标签:
4条回答
  • 2020-12-02 00:36

    ipython, which you're using instead of the normal Python interactive shell, traps all exceptions itself and does NOT use sys.excepthook. Run it as ipython -pdb instead of just ipython, and it will automatically invoke pdb upon uncaught exceptions, just as you are trying to do with your excepthook.

    0 讨论(0)
  • 2020-12-02 00:38

    Five years after you wrote this, IPython still works this way, so I guess a solution might be useful to people googling this.

    IPython replaces sys.excepthook every time you execute a line of code, so your overriding of sys.excepthook has no effect. Furthermore, IPython doesn't even call sys.excepthook, it catches all exceptions and handles them itself before things get that far.

    To override the exception handler whilst IPython is running, you can monkeypatch over their shell's showtraceback method. For example, here's how I override to give what looks like an ordinary Python traceback (because I don't like how verbose IPython's are):

    def showtraceback(self):
        traceback_lines = traceback.format_exception(*sys.exc_info())
        del traceback_lines[1]
        message = ''.join(traceback_lines)
        sys.stderr.write(message)
    
    import sys
    import traceback
    import IPython
    IPython.core.interactiveshell.InteractiveShell.showtraceback = showtraceback
    

    This works in both the normal terminal console and the Qt console.

    0 讨论(0)
  • 2020-12-02 00:45

    expanding on Chris answer, you can use another function like a decorator to add your own functionality to jupyters showbacktrace:

    from IPython.core.interactiveshell import InteractiveShell
    from functools import wraps
    import traceback
    import sys
    
    def change_function(func):
        @wraps(func)
        def showtraceback(*args, **kwargs):
            # extract exception type, value and traceback
            etype, evalue, tb = sys.exc_info()
            if issubclass(etype, Exception):
                print('caught an exception')
            else:
                # otherwise run the original hook
                value = func(*args, **kwargs)
                return value
        return showtraceback
    
    InteractiveShell.showtraceback = change_function(InteractiveShell.showtraceback)
    
    raise IOError
    
    0 讨论(0)
  • 2020-12-02 00:53

    See this SO question and make sure there isn't something in your sitecustomize.py that prevents debugging in interactive mode.

    0 讨论(0)
提交回复
热议问题