我正在 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
如果您希望在 debug
为 False
时看到通常的回溯错误消息,那么上面的内容可以简化为
if debug:
sys.excepthook = lambda type_, value, traceback: pdb.set_trace()
关于Python:如何让代码适用于所有失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28155161/