Launch an IPython shell on exception

前端 未结 10 2378
长情又很酷
长情又很酷 2020-12-04 09:30

Is there a way to launch an IPython shell or prompt when my program runs a line that raises an exception?

I\'m mostly interested in the context, variables, in the sc

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 10:04

    If you want to both get the traceback and open a IPython shell with the environment at the point of the exception:

    def exceptHook(*args):
        '''A routine to be called when an exception occurs. It prints the traceback
        with fancy formatting and then calls an IPython shell with the environment
        of the exception location.
        '''
        from IPython.core import ultratb
        ultratb.FormattedTB(call_pdb=False,color_scheme='LightBG')(*args)
        from IPython.terminal.embed import InteractiveShellEmbed
        import inspect
        frame = inspect.getinnerframes(args[2])[-1][0]
        msg   = 'Entering IPython console at {0.f_code.co_filename} at line {0.f_lineno}'.format(frame)
        savehook = sys.excepthook # save the exception hook
        InteractiveShellEmbed()(msg,local_ns=frame.f_locals,global_ns=frame.f_globals)
        sys.excepthook = savehook # reset IPython's change to the exception hook
    
    import sys
    sys.excepthook = exceptHook
    

    Note that it is necessary to pull than namespace information from the last frame referenced by the traceback (arg[2])

提交回复
热议问题