gpt4 book ai didi

python - sys.excepthook 在导入的模块中不起作用

转载 作者:太空狗 更新时间:2023-10-30 00:08:27 35 4
gpt4 key购买 nike

我正在尝试设计一个 Python 程序,使用日志记录模块记录所有未捕获的异常。我通过使用 sys.excepthook 函数来覆盖默认的异常处理来做到这一点。我注意到如果我直接从命令行运行该程序,它工作正常,但如果我尝试导入文件,它就不起作用。似乎 sys.excepthook 函数不知道日志记录模块。这是一个例子:

#! /usr/bin/env python2.7
import logging, sys

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.FileHandler("test.log"))

print "outside of exception handler: logger = %s" % logger

def handleException(excType, excValue, traceback):
#global logger # this function doesn't work whether or not I include this line
print "inside exception handler: logger = %s" % logger
logger.error("Uncaught exception", exc_info=(excType, excValue, traceback))

sys.excepthook = handleException

logger.debug("starting")
asdf # create an exception

如果我从命令行 (./loggingTest.py) 运行它,它工作正常。记录了异常,我看到了这个输出:

outside of exception handler: logger = <logging.RootLogger object at 0x7f2022eab950>
inside exception handler: logger = <logging.RootLogger object at 0x7f2022eab950>

但是,如果我运行 Python 解释器并尝试导入文件 (import loggingTest),它的行为会很奇怪。异常没有被记录,我看到了这个:

outside of exception handler: logger = <logging.RootLogger object at 0x7f8ab04f3ad0>
inside exception handler: logger = None
Error in sys.excepthook:
Traceback (most recent call last):
File "loggingTest.py", line 13, in handleException
logger.error("Uncaught exception", exc_info=(excType, excValue, traceback))
AttributeError: 'NoneType' object has no attribute 'error'

Original exception was:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "loggingTest.py", line 18, in <module>
asdf # create an exception
NameError: name 'asdf' is not defined

我也许可以通过在 sys.excepthook 中再次导入日志记录模块来解决这个问题,但我仍然很好奇:为什么会这样?

最佳答案

我将此问题报告为 Python bug tracker 上的错误.到目前为止,有人回应说 Python 2.7 和 2.7.1 之间肯定有变化,他认为这是预期的行为。他建议这样记录所有异常:

def handleException(excType, excValue, traceback, logger=logger):
logger.error("Uncaught exception", exc_info=(excType, excValue, traceback))

sys.excepthook = handleException

关于python - sys.excepthook 在导入的模块中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5451746/

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