Python:如何让代码适用于所有失败

标签 python debugging pdb try-except

我正在 python 中使用 pdb 模块;我最近才知道它,所以我是一个初学者。我想要做的是有一个变量,如果为 True,将对脚本中发生的所有失败调用 set_trace(),而不将其全部放入 try/except 语句中。例如,我想要以下功能而不需要 try/except:

from pdb import set_trace

debug = True
try:
    #entire script here

except Exception, e:
    if debug:
        set_trace()
    else:
        print e

有没有一种方法可以在没有巨大的 try except 语句的情况下执行此操作(也不必为每个可能失败的命令执行 if 语句)?

谢谢。

最佳答案

您可以自定义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


import sys
import pdb

debug = True

def excepthook(type_, value, traceback):
    if debug:
        pdb.set_trace()
    else:
        print(value)
        # Per mgilson's suggestion, to see the full traceback error message
        # sys.__excepthook__(type_, value, traceback)   

sys.excepthook = excepthook

1 / 0

如果您希望在 debugFalse 时看到通常的回溯错误消息,那么上面的内容可以简化为

if debug:
    sys.excepthook = lambda type_, value, traceback: pdb.set_trace() 

关于Python:如何让代码适用于所有失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28155161/

相关文章:

python - 得到一个似乎没有多大意义的错误。

python - 如何使用pdb调试C写的模块?

python - 带有自定义按钮的 QStyledItemDelegate

python - 在 Python 中重新加载整个包结构

python - 如何强制 scipy 使用 Adams 进行集成?

android - Eclipse Android Debugger - 在我的代码中哪里导致了异常?

python - 如何使用主导标签库在td中使用rowspan?

visual-studio-2008 - 尝试在Chrome和Firefox中调试npapi插件,但未成功,正确的方法是什么?

php - PHP解析/语法错误;以及如何解决它们

python - Python 的 rdb 调试断点处不存在局部变量(在 celery 任务中)