gpt4 book ai didi

python - Jupyter Python 中的异常捕获器不起作用(sys.excepthook)

转载 作者:行者123 更新时间:2023-12-03 08:25:20 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





cannot override sys.excepthook

(5 个回答)


5年前关闭。




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

# 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

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

谢谢!

最佳答案

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

更改 sys.excepthook不适用于 iPython。

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

你会在一些项目中找到额外的解释和修复的实现,例如 danrobinson/tracestack .

关于python - Jupyter Python 中的异常捕获器不起作用(sys.excepthook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43498982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com