Python回溯,显示发生错误的行,即使不显示完整的回溯
如何确保打印出失败的实际行而不包括整个回溯?回溯对我来说可能太长了太多打印出来了 这段代码只打印函数a和b中的错误,但我希望看到实际的错误发生在函数d中Python回溯,显示发生错误的行,即使不显示完整的回溯,python,error-handling,Python,Error Handling,如何确保打印出失败的实际行而不包括整个回溯?回溯对我来说可能太长了太多打印出来了 这段代码只打印函数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
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)
只需使用
traceback.format_exc()
而不是traceback.format_exc(2)
。所采用的参数是要格式化的条目数的限制。如果你不写,它们都是格式化的
请注意,print traceback.format\u exc()
也可以简单地写为traceback.print\u exc()
如果您只想显示回溯:
print(traceback.format_exc())
error_type, error, tb = sys.exc_info()
filename, lineno, func_name, line = traceback.extract_tb(tb)[-1]
如果要从回溯中提取函数名称、行编号、错误描述等值:
print(traceback.format_exc())
error_type, error, tb = sys.exc_info()
filename, lineno, func_name, line = traceback.extract_tb(tb)[-1]