Launch an IPython shell on exception

前端 未结 10 2355
长情又很酷
长情又很酷 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条回答
  • 2020-12-04 09:40

    Doing:

    ipython --pdb -c "%run exceptionTest.py"
    

    kicks off the script after IPython initialises and you get dropped into the normal IPython+pdb environment.

    0 讨论(0)
  • 2020-12-04 09:40

    You can try this:

    from ipdb import launch_ipdb_on_exception
    
    def main():
        with launch_ipdb_on_exception():
            # The rest of the code goes here.
            [...]
    
    0 讨论(0)
  • 2020-12-04 09:44

    ipdb integrates IPython features into pdb. I use the following code to throw my apps into the IPython debugger after an unhanded exception.

    import sys, ipdb, traceback
    
    def info(type, value, tb):
        traceback.print_exception(type, value, tb)
        ipdb.pm()
    
    sys.excepthook = info
    
    0 讨论(0)
  • 2020-12-04 09:53

    @Adam's works like a charm except that IPython loads a bit slowly(800ms on my machine). Here I have a trick to make the load lazy.

    class ExceptionHook:
        instance = None
    
        def __call__(self, *args, **kwargs):
            if self.instance is None:
                from IPython.core import ultratb
                self.instance = ultratb.FormattedTB(mode='Verbose',
                     color_scheme='Linux', call_pdb=1)
            return self.instance(*args, **kwargs)
    sys.excepthook = ExceptionHook()
    

    Now we don't need to wait at the very beginning. Only when the program crashes will cause IPython to be imported.

    0 讨论(0)
  • 2020-12-04 09:55

    You can do something like the following:

    import sys
    from IPython.Shell import IPShellEmbed
    ipshell = IPShellEmbed()
    
    def excepthook(type, value, traceback):
        ipshell()
    
    sys.excepthook = excepthook
    

    See sys.excepthook and Embedding IPython.

    0 讨论(0)
  • 2020-12-04 09:59

    This man page says iPython has --[no]pdb option to be passed at command line to start iPython for uncaught exceptions. Are you looking for more?

    EDIT: python -m pdb pythonscript.py can launch pdb. Not sure about similar thing with iPython though. If you are looking for the stack trace and general post-mortem of the abnormal exit of program, this should work.

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