如何打印异常对象的堆栈跟踪,例如 的返回值concurrent.futures.Future.exception()?大多数traceback和sys异常函数依赖于“当前正在处理”的隐式异常(这包括sys.exc_info、traceback.print_exc、traceback.format_exc)。异常已经被处理,并作为对象返回,所以这些对我来说毫无价值。有几个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()))
Run Code Online (Sandbox Code Playgroud)
如何打印异常对象的堆栈跟踪,例如 的返回值concurrent.futures.Future.exception()?
有一个exception方法返回调用引发的异常。因此,您可以像从任何其他异常( Python 3.5+ )一样从中获取回溯。使用traceback.TracebackException它(只需替换ex为您的例外):
print("".join(traceback.TracebackException.from_exception(ex).format())
Run Code Online (Sandbox Code Playgroud)
执行此操作的扩展示例和其他功能:
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()))
Run Code Online (Sandbox Code Playgroud)
输出将类似于:
True
Traceback (most recent call last):
File "untidsfsdfsdftled.py", line 29, in <module>
1/0
ZeroDivisionError: division by zero
Run Code Online (Sandbox Code Playgroud)