python - 像php的set_error_handler一样在脚本中处理所有错误
Python有没有一种“通用”的解决方案,可以在脚本中任何地方发生错误或异常时,把这个错误传递给一个自定义的函数,就像PHP的set_error_handler()函数那样?
我知道try/catch这种方法,但它有点麻烦,因为try/catch只对它里面的代码有效。
def sample_function():
# some code that causes error, breaks script, does not pass error back to try/catch
try:
sample_function()
except Exception, e:
print str(e)
我想要一个简单的try/except,能够处理所有错误,即使错误是在一个函数中触发的,而这个函数又是在另一个函数中调用的,而不需要把每一段代码都用try/except包起来。
有没有人知道这样做是否可能?