gpt4 book ai didi

Python traceback,显示错误发生的行,即使没有显示完整的 traceback

转载 作者:行者123 更新时间:2023-11-28 17:45:51 29 4
gpt4 key购买 nike

如何确保在不包括整个回溯的情况下打印出失败的实际行?追溯对我来说可能太长了,所以我也把它全部打印出来。

此代码仅打印函数 a 和 b 中的错误,但我想查看实际错误发生在函数 d 中。

import traceback
def a():
try:
return b();
except:
print traceback.format_exc(2)

def b():
return c();

def c():
return d();

def d():
x = 1/0

a()

最佳答案

你可以这样做:

import sys
import traceback

def a():
try:
return b();
except:
_, _, tb = sys.exc_info()
print traceback.format_list(traceback.extract_tb(tb)[-1:])[-1]

或者你自己格式化字符串:

import sys
import traceback

def a():
try:
return b();
except:
_, _, tb = sys.exc_info()
filename, lineno, funname, line = traceback.extract_tb(tb)[-1]
print '{}:{}, in {}\n {}'.format(filename, lineno, funname, line)

This function returns a tuple of three values that give information about the exception that is currently being handled (...) If no exception is being handled anywhere on the stack, a tuple containing three None values is returned. Otherwise, the values returned are (type, value, traceback).

Return a list of up to limit “pre-processed” stack trace entries extracted from the traceback object traceback. It is useful for alternate formatting of stack traces. If limit is omitted or None, all entries are extracted. A “pre-processed” stack trace entry is a quadruple (filename, line number, function name, text) representing the information that is usually printed for a stack trace. The text is a string with leading and trailing whitespace stripped; if the source is not available it is None.

Given a list of tuples as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None.

关于Python traceback,显示错误发生的行,即使没有显示完整的 traceback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18380033/

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