Jupyter Python中的异常捕手无法正常工作(sys.excepthook)

时间:2017-04-19 14:42:39

标签: python logging error-handling exception-handling sys

我正在尝试捕获所有异常并使用以下代码将它们记录到日志文件中,但由于某种原因它不能捕获它们。代码是:

# Prepares logging
import logging
import time
output_folder='whatever'
# Logging to file:
today=time.strftime("%Y%M%d %H:%M:%S")
logging.basicConfig(filename=output_folder+'/logger '+today+'.log',level=logging.DEBUG,
                    format='%(asctime)s %(message)s', filemode='w')
logging.info('Program started.')

# Every time there is an error, catch it
import sys
#def error_catching(exctype, value, tb):
def log_uncaught_exceptions(ex_cls, ex, tb):
    print "Error found"
    logging.critical(''.join(traceback.format_tb(tb)))
    logging.critical('{0}: {1}'.format(ex_cls, ex))

sys.excepthook = log_uncaught_exceptions

然后我生成一个错误,例如通过调用一个不存在的变量(' m')并且我得到错误但是没有任何东西登录到日志记录文件中:

m #this should generate a NameError, which is the following

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-9-69b64623f86d> in <module>()
----> 1 m

NameError: name 'm' is not defined

而且,如上所述,日志文件没有捕获任何内容。我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

免责声明:显然,开放赏金的问题无法结束。因此,我的答案主要基于this other similar question/answer

更改private void listViewItem_MouseDown(object sender, MouseButtonEventArgs e) { Application.Current.Dispatcher.BeginInvoke(new Action(() => { MessageBox.Show("ROW CLICKED"); })); } 不适用于iPython。

解决方法是更新IPython.core.interactiveshell.InteractiveShell.showtraceback

您会在danrobinson/tracestack等某些项目中找到有关它的其他解释和修复实现。