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

saf*_*fsd 7 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?我可以更改配置文件吗?我不想包装我的代码来执行此操作.

Vin*_*vic 19

这就是你需要的

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
Run Code Online (Sandbox Code Playgroud)

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

# 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
Run Code Online (Sandbox Code Playgroud)

第三个(它总是启动调试器,除非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
Run Code Online (Sandbox Code Playgroud)