如何设置 sys.excepthook 在 python 中全局调用 pdb?
来自 Python 文档:
sys.excepthook(类型、值、回溯)
此函数将给定的回溯和异常打印到
sys.stderr
。当引发异常但未捕获时,解释器会使用三个参数调用 sys.excepthook:异常类、异常实例和回溯对象。 在交互式会话中,这发生在控制权返回提示之前; 在 Python 程序中,这发生在程序退出之前。 可以通过将另一个三参数函数分配给
sys.excepthook
来自定义此类顶级异常的处理。
http://docs.python.org/library/sys.html
我该如何全局修改此设置,以便默认操作始终调用 pdb
? 有我可以更改的配置文件吗? 我不想包装我的代码来执行此操作。
From Python docs:
sys.excepthook(type, value, traceback)
This function prints out a given traceback and exception to
sys.stderr
.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 tosys.excepthook
.
http://docs.python.org/library/sys.html
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是您需要的
http://ynniv.com/blog/2007/11/debugging -python.html
三种方式,第一种简单粗暴(Thomas Heller) - 将以下内容添加到 site-packages/sitecustomize.py:
第二个更复杂,并检查交互模式(奇怪的是跳过交互模式下的调试),来自 cookbook:
第三个(除非 stdin 或 stderr 被重定向,否则总是启动调试器) ynniv
Here's what you need
http://ynniv.com/blog/2007/11/debugging-python.html
Three ways, the first is simple but crude (Thomas Heller) - add the following to site-packages/sitecustomize.py:
The second is more sophisticated, and checks for interactive mode (weirdly skipping the debugging in interactive mode), from the cookbook:
And the third (which always start the debugger unless stdin or stderr are redirected) by ynniv
另一种选择是使用 ipython,我认为它是任何 python 开发人员的必备工具。 不要从 shell 运行脚本,而是使用 %run 从 ipython 运行脚本。 当出现异常时,可以输入%debug进行调试。 (还有一个选项可以自动调试发生的任何异常,但我忘记了它是什么。)
Another option is to use ipython, which I consider a must-have tool for any python developer anyway. Instead of running your script from the shell, run it from ipython with %run. When an exception occurs, you can type %debug to debug it. (There's also an option to automatically debug any exception that occurs, but I forget what it is.)
尝试:
Try: