引发异常时如何修改 Python 回溯对象? [英] How can I modify a Python traceback object when raising an exception?

查看:51
本文介绍了引发异常时如何修改 Python 回溯对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 Python 库,第三方开发人员使用它来为我们的核心应用程序编写扩展.

I'm working on a Python library used by third-party developers to write extensions for our core application.

我想知道是否可以在引发异常时修改回溯,因此最后一个堆栈帧是对开发人员代码中库函数的调用,而不是库中引发异常的行.堆栈底部还有一些帧,其中包含对首次加载我希望删除的代码时使用的函数的引用.

I'd like to know if it's possible to modify the traceback when raising exceptions, so the last stack frame is the call to the library function in the developer's code, rather than the line in the library that raised the exception. There are also a few frames at the bottom of the stack containing references to functions used when first loading the code that I'd ideally like to remove too.

提前感谢您的建议!

推荐答案

不改变回溯怎么样?您请求的两件事都可以通过不同的方式更轻松地完成.

What about not changing the traceback? The two things you request can both be done more easily in a different way.

  1. 如果在开发人员的代码中捕获了库中的异常并引发了新的异常,那么原始回溯当然会被丢弃.这就是异常通常的处理方式......如果您只允许引发原始异常但您修改它以删除所有上"帧,则实际异常将没有意义,因为回溯中的最后一行不会本身能够引发异常.
  2. 要去掉最后几帧,您可以请求缩短回溯...像 traceback.print_exception() 之类的东西采用限制"参数,您可以使用它来跳过最后几个条目.

也就是说,如果您真的需要,应该很有可能修改回溯……但是您会在哪里做呢?如果在最顶层的一些包装器代码中,那么您可以简单地获取回溯,取一个切片以删除您不想要的部分,然后使用回溯"模块中的函数根据需要进行格式化/打印.

That said, it should be quite possible to munge the tracebacks if you really need to... but where would you do it? If in some wrapper code at the very top level, then you could simply grab the traceback, take a slice to remove the parts you don't want, and then use functions in the "traceback" module to format/print as desired.

这篇关于引发异常时如何修改 Python 回溯对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆