Python - 在异常被抛出时启动交互式调试器

Neu*_*onQ 15 python debugging pdb

有没有办法让python程序启动一个交互式调试器,比如import pdb; pdb.set_trace()实际抛出一个异常?

我知道使这项工作有困难,但它比一个巨大的堆栈跟踪更有价值,之后我必须用它来确定插入断点的位置,然后重新启动程序来调试它.我知道只是让调试器启动而不是抛出异常是没有意义的,因为任何异常都可以在一个级别或另一个级别捕获,所以如果我只能选择一个异常列表,交互式调试会话将启动而不是它们被抛出(因为我知道这个列表中的例外实际上是"错误",之后不会有任何有意义的程序行为)......

我听说Common Lisp有这样的东西,但我不知道它是如何工作的,只是"真正的lispers"赞美了很多......

Bor*_*lik 14

最简单的方法是将整个代码包装在一个try块中,如下所示:

if __name__ == '__main__':

    try:
        raise Exception()
    except:
        import pdb
        pdb.set_trace()
Run Code Online (Sandbox Code Playgroud)

有一个更复杂的解决方案,用于sys.excepthook覆盖未捕获的异常的处理,如 本配方中所述:

## {{{ http://code.activestate.com/recipes/65287/ (r5)
# code snippet, to be included in 'sitecustomize.py'
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()

sys.excepthook = info
## end of http://code.activestate.com/recipes/65287/ }}}
Run Code Online (Sandbox Code Playgroud)

上面的代码应该包含在一个名为sitecustomize.pyinside site-packagesdirectory 的文件中,该文件由python自动导入.调试器仅在python以非交互模式运行时启动.


dan*_*rth 5

这个问题很老了,所以这主要是为了将来我

try:
    ...
except:
    import traceback, pdb, sys
    traceback.print_exc()
    print ''
    pdb.post_mortem()
    sys.exit(1)
Run Code Online (Sandbox Code Playgroud)