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)
注意跟踪是如何在产生异常的函数处结束的。