7

来自 Python 文档:

sys.excepthook(type, value, traceback)

此函数将给定的回溯和异常打印到sys.stderr.

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

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

如何全局修改它,以便默认操作是始终调用pdb?有我可以更改的配置文件吗?我不想包装我的代码来做到这一点。

4

3 回答 3

21

这是你需要的

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

第二个更复杂,并从食谱中检查交互模式(奇怪地跳过了交互模式下的调试) :

# 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
于 2009-08-06T07:27:07.777 回答
1

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

于 2009-08-26T17:48:08.450 回答
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()
于 2009-08-06T07:31:43.417 回答