如何设置sys.excepthook以在python中全局调用pdb?

时间:2009-08-06 07:15:46

标签: python debugging configuration pdb

来自Python文档:

  

sys.excepthook(type, value, traceback)

     

此函数将给定的追溯和例外打印到sys.stderr

     

当引发异常并且未被捕获时,解释器使用三个参数调用sys.excepthook,异常类,异常实例和回溯对象。在交互式会话中,这发生在控制返回到提示之前;在Python程序中,这发生在程序退出之前。可以通过将另一个三参数函数分配给sys.excepthook来自定义处理此类顶级异常。

http://docs.python.org/library/sys.html

如何全局修改此设置,以便默认操作是始终调用pdb?我可以更改配置文件吗?我不想包装我的代码来执行此操作。

3 个答案:

答案 0 :(得分:17)

这就是你需要的东西

http://ynniv.com/blog/2007/11/debugging-python.html

三种方式,第一种方式是简单但粗略的(Thomas Heller) - 将以下内容添加到site-packages / sitecustomize.py:

import pdb, sys, traceback
def info(type, value, tb):
    traceback.print_exception(type, value, tb)
    pdb.pm()
sys.excepthook = info

第二个更复杂,并从cookbook

检查交互模式(奇怪地跳过交互模式下的调试)
# 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

第三个(总是启动调试器,除非stdin或stderr被重定向)ynniv

# code snippet, to be included in 'sitecustomize.py'
import sys

def info(type, value, tb):
   if (#hasattr(sys, "ps1") or
       not sys.stderr.isatty() or 
       not sys.stdin.isatty()):
       # stdin or stderr is redirected, just do the normal thing
       original_hook(type, value, tb)
   else:
       # a terminal is attached and stderr is not redirected, debug 
       import traceback, pdb
       traceback.print_exception(type, value, tb)
       print
       pdb.pm()
       #traceback.print_stack()

original_hook = sys.excepthook
if sys.excepthook == sys.__excepthook__:
    # if someone already patched excepthook, let them win
    sys.excepthook = info

答案 1 :(得分:1)

另一种选择是使用ipython,我认为这是任何python开发人员必备的工具。而不是从shell运行脚本,使用%run从ipython运行它。发生异常时,您可以键入%debug来调试它。 (还有一个选项可以自动调试发生的任何异常,但我忘了它是什么。)

答案 2 :(得分:0)

尝试:

import pdb
import sys

def excepthook(type, value, traceback):
    pdb.post_mortem(traceback)

excepthook.old = sys.excepthook
sys.excepthook = excepthook

def raise_exception():
    raise_exception()

raise_exception()