Starting python debugger automatically on error

前端 未结 13 2262
南方客
南方客 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:17

    Use the following module:

    import sys
    
    def info(type, value, tb):
        if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like
        # device, so we call the default hook
            sys.__excepthook__(type, value, tb)
        else:
            import traceback, pdb
            # we are NOT in interactive mode, print the exception...
            traceback.print_exception(type, value, tb)
            print
            # ...then start the debugger in post-mortem mode.
            # pdb.pm() # deprecated
            pdb.post_mortem(tb) # more "modern"
    
    sys.excepthook = info
    

    Name it debug (or whatever you like) and put it somewhere in your python path.

    Now, at the start of your script, just add an import debug.

提交回复
热议问题