如何设置sys.excepthook在python中全局调用pdb? [英] How do I set sys.excepthook to invoke pdb globally in python?
问题描述
从Python文档:
sys.excepthook(type,value,traceback)
此函数打印给定的跟踪和异常 sys.stderr
。
This function prints out a given traceback and exception to sys.stderr
.
当引发异常和未捕获异常时,解释器使用三个参数调用 sys.excepthook
,异常类,异常实例和跟踪目的。在交互会话中,这发生在控制返回到提示之前;在Python程序中,这发生在程序退出之前。这种顶级异常的处理可以通过为 sys.excepthook
分配另一个三参数函数来定制。
When an exception is raised and uncaught, the interpreter calls sys.excepthook
with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook
.
http://docs.python.org/library/sys .html
如何在全局范围内修改它,所以默认操作是总是调用 pdb
?有没有可以更改的配置文件?
How do I modify this globally so the default action is to always invoke pdb
? Is there a configuration file I can change? I don't want to wrap my code to do this.
推荐答案
这里是你需要的
http://ynniv.com/blog/2007 /11/debugging-python.html
三种方法,第一种是简单但粗糙的( Thomas Heller ) - 将以下内容添加到site-packages / sitecustomize.py:
Three ways, the first is simple but crude (Thomas Heller) - add the following to 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 :
The second is more sophisticated, and checks for interactive mode (weirdly skipping the debugging in interactive mode), from the 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
And the third (which always start the debugger unless stdin or stderr are redirected) by 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
这篇关于如何设置sys.excepthook在python中全局调用pdb?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!