Starting python debugger automatically on error

前端 未结 13 2285
南方客
南方客 2020-11-27 08:44

This is a question I have wondered about for quite some time, yet I have never found a suitable solution. If I run a script and I come across, let\'s say an IndexError, pyth

13条回答
  •  野性不改
    2020-11-27 09:36

    You can use traceback.print_exc to print the exceptions traceback. Then use sys.exc_info to extract the traceback and finally call pdb.post_mortem with that traceback

    import pdb, traceback, sys
    
    def bombs():
        a = []
        print a[0]
    
    if __name__ == '__main__':
        try:
            bombs()
        except:
            extype, value, tb = sys.exc_info()
            traceback.print_exc()
            pdb.post_mortem(tb)
    

    If you want to start an interactive command line with code.interact using the locals of the frame where the exception originated you can do

    import traceback, sys, code
    
    def bombs():
        a = []
        print a[0]
    
    if __name__ == '__main__':
        try:
            bombs()
        except:
            type, value, tb = sys.exc_info()
            traceback.print_exc()
            last_frame = lambda tb=tb: last_frame(tb.tb_next) if tb.tb_next else tb
            frame = last_frame().tb_frame
            ns = dict(frame.f_globals)
            ns.update(frame.f_locals)
            code.interact(local=ns)
    

提交回复
热议问题