我有以下代码:
# exc is a local variable of type Exception
# This is not inside an except block
if isinstance(exc, ClientError):
logging.debug("ClientError raised while loading %s:\n%s", package.id, traceback.format_exc())
continue
当运行此代码并且 exc
的类型为 ClientError
时,format_exc()
仅打印出 NoneType: None
code> 因为当前没有异常正在处理(代码不在 except
block 内)。幸运的是,traceback
上似乎有一个 format_exception
方法,该方法与当前正在处理的异常无关,但为了调用它,我需要提取类型、值和 tb 来 self 的异常变量。我该怎么做?
最佳答案
exc
是如何产生的?如果它是从某个没有相应堆栈的函数返回的,那么无论如何都不可能产生正确的帧。最重要的是,如果没有 going deep into ctypes
就不可能生成 Traceback
对象。 ,所以这可能不是我们想要的。
如果您所追求的实际上是记录异常的堆栈,请使用 inspect.currentframe
和 traceback.format_stack
可能会产生你可能想要的东西。但是,如前所述,您需要获取尽可能靠近错误发生位置的帧。考虑这个例子:
import traceback
import inspect
import logging
class Client:
pass
class ClientError(Exception):
pass
def get_client(name):
if name is None:
return ClientError('client must have a name')
return Client()
def connect(target, name=None):
exc = get_client(name)
if isinstance(exc, ClientError):
frames = inspect.currentframe()
logging.debug("ClientError raised while loading %s:\n%s",
target, ''.join(traceback.format_stack(frames)))
def main():
connect('somewhere')
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
main()
执行此命令将产生以下输出:
DEBUG:root:ClientError raised while loading somewhere:
File "foo.py", line 34, in <module>
main()
File "foo.py", line 30, in main
connect('somewhere')
File "foo.py", line 26, in connect
target, ''.join(traceback.format_stack(frames)))
请注意,堆栈恰好在调用完成的位置结束,因为 current_frame
的返回值仅限于 frames
。这就是为什么应该在生成堆栈的地方生成堆栈并对其进行格式化,然后后退一级。考虑这些更新的功能:
def get_client(name):
if name is None:
return (
ClientError('client must have a name'),
traceback.format_stack(inspect.currentframe().f_back),
)
return Client(), None
def connect(target, name=None):
exc, frames = get_client(name)
if isinstance(exc, ClientError):
stack = ''.join(frames)
logging.debug("ClientError raised while loading %s:\n%s",
target, stack)
执行
$ python foo.py
DEBUG:root:ClientError raised while loading somewhere:
File "foo.py", line 37, in <module>
main()
File "foo.py", line 33, in main
connect('somewhere')
File "foo.py", line 25, in connect
exc, frames = get_client(name)
注意跟踪如何在产生异常的函数处结束。
关于python - 当我不处理异常时如何打印异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48902791/