最简单的方法是将整个代码包装在这样的try
块中:
if __name__ == '__main__':
try:
raise Exception()
except:
import pdb
pdb.set_trace()
有一个更复杂的解决方案用于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/ }}}
上面的代码应该包含在一个名为sitecustomize.py
inside site-packages
directory 的文件中,该文件由 python 自动导入。调试器仅在 python 以非交互模式运行时启动。