如何设置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
第二个是更多复杂和检查互动模式(以交互方式奇怪地跳过调试),从食谱:
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屋!