【问题标题】:Exception catcher in Jupyter Python not working (sys.excepthook) [duplicate]Jupyter Python中的异常捕获器不起作用(sys.excepthook)[重复]
【发布时间】:2017-09-15 21:00:16
【问题描述】:

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

# 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

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

谢谢!

【问题讨论】:

  • 我不确定 iPython 是否依赖这个钩子。我认为它本身就有一个钩子。如果在接下来的 24 小时内没有提供任何答案,我会尝试写一个更好的答案。
  • stackoverflow.com/questions/1261668/…(可能重复的问题...)
  • Josay,感谢您的 cmets。尽管标记为重复的答案有一些共同点,但该问题中选择的答案不是正确答案,可能是您的答案。将尝试您的方法并回复您。

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


【解决方案1】:

免责声明:显然,无法关闭悬赏问题。因此,我的回答主要基于this other similar question/answer

更改 sys.excepthook 在 iPython 上不起作用。

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

您会在某些项目(例如danrobinson/tracestack)中找到额外的解释和修复的实现。

【讨论】:

  • 这看起来很棒。谢谢@Josay
猜你喜欢
  • 1970-01-01
  • 2019-06-09
  • 2022-01-22
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
  • 2012-07-13
相关资源
最近更新 更多