gpt4 book ai didi

Python:如何在没有 "currently being handled"异常的情况下打印异常对象的堆栈跟踪?

转载 作者:行者123 更新时间:2023-12-01 02:18:25 24 4
gpt4 key购买 nike

如何打印异常对象的堆栈跟踪,例如 concurrent.futures.Future.exception() 的返回值?大多数 tracebacksys 异常函数依赖于“当前正在处理”的隐式异常(这包括 sys.exc_info >traceback.print_exctraceback.format_exc)。异常已经被处理,并作为对象返回,所以这些对我来说毫无值(value)。有几个 traceback 函数接受异常参数,但它们要么不提供堆栈跟踪输出,要么需要一个回溯对象作为输入,而我没有。我当然可以创建一个回溯对象,但该对象不会包含我需要的信息。

是的,我知道这里有很多关于打印异常堆栈跟踪的问答。我已经搜索过了。这个问题与那些问题完全不同。

这是我正在尝试做的事情的一个例子。

with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
for idx in range(0, 10):
future = executor.submit(third_party_script.main)
threads.append(future)

for future in threads:
if(future.exception()):
print(magic_traceback_function(future.exception()))

如何打印异常对象的堆栈跟踪,例如 concurrent.futures.Future.exception() 的返回值?

最佳答案

exception返回调用引发的异常的方法。因此,您可以像从任何其他异常 (Python 3.5+) 中一样从中获取回溯。使用traceback.TracebackException对于它(只需将 ex 替换为您的异常(exception)):

print("".join(traceback.TracebackException.from_exception(ex).format())

用于执行此操作的扩展示例和其他功能:

import traceback

try:
1/0
except Exception as ex:
print("".join(traceback.TracebackException.from_exception(ex).format()) == traceback.format_exc() == "".join(traceback.format_exception(type(ex), ex, ex.__traceback__)))
print("".join(traceback.TracebackException.from_exception(ex).format()))

输出将类似于:

True
Traceback (most recent call last):
File "untidsfsdfsdftled.py", line 29, in <module>
1/0
ZeroDivisionError: division by zero

关于Python:如何在没有 "currently being handled"异常的情况下打印异常对象的堆栈跟踪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48161387/

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