Python拓展1(traceback模块及sys.exc_info() :跟踪异常返回信息)
traceback模块
作用:traceback模块被用来跟踪异常返回信息
import traceback # 调用traceback模块 try: if str(123) > 5: print('这是一个无法执行的错误') except Exception: traceback.print_exc() # 返回错误信息 # 控制台输出结果: # Traceback (most recent call last): # File "D:/pycharm/S9/pythontext/main.py", line 27, in <module> # if str(123) > 5: # TypeError: '>' not supported between instances of 'str' and 'int'
类似在没有try……except之前,出现异常解释器报错形式。
此报错信息也可以直接存储在文件中!
import traceback # 调用traceback模块 try: if str(123) > 5: print('这是一个无法执行的错误') except Exception: traceback.print_exc(file=open('log.log', mode='a', encoding='utf-8')) # file打开或创建一个名为log.log的文件以追加形式填入报错 # 文件内内容与上程序控制台输出的相同
关于traceback.prit_exc()和traceback.format_exc()区别
format_exc() 返回字符串
print_exc() 直接给打印出来
故 traceback.print_exc() 与 print (traceback.format_exc()) 显示效果是一样的
PS:但print_exc()还可以接受file参数直接写入到一个文件中。
例如:traceback.print_exc(file=open('log.log', mode='a', encoding='utf-8'))
将文件写入到了log.log文件中
sys.exc_info() 返回错误信息方法
返回 (type, value, traceback)实际为一个元组 type为异常类型, value为异常的参数(通常为异常错误的信息), traceback调用堆栈封装在最初发生异常的地方
1 import sys 2 try: 3 if str(123) > 5: 4 print('这是一个无法执行的错误') 5 except Exception: 6 exc_type, exc_value, exc_traceback = sys.exc_info() 7 print('以下为代码错误信息:') 8 print('exc_type(异常类型): {}\nexc_value(异常错误的信息): {}\nexc_traceback(调用堆栈封装在最初发生异常的地方): {}'.format(exc_type, exc_value, exc_traceback)) 9 # 控制台输出结果 10 # 以下为代码错误信息: 11 # exc_type(异常类型): <class 'TypeError'> 12 # exc_value(异常错误的信息): '>' not supported between instances of 'str' and 'int' 13 # exc_traceback(调用堆栈封装在最初发生异常的地方): <traceback object at 0x02A81648>
traceback.print_tb格式化输出错误
1 import sys 2 import traceback 3 # 以下是两个函数嵌套 4 def lumberjack(): 5 bright_side_of_death() 6 7 def bright_side_of_death(): 8 return tuple()[0] 9 # 以下是异常处理 10 try: 11 lumberjack() 12 except IndexError: 13 exc_type, exc_value, exc_traceback = sys.exc_info() # 分别接收sys.exc_info的三个元素 14 print("*** print_tb:的使用") 15 traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) 16 traceback.print_tb(exc_traceback, limit=None, file=open('log.log', mode='a', encoding='utf-8')) 17 # exc_traceback 调用堆栈封装在最初发生异常的地方 18 # limit= 此处显示需要显示的回溯的层级,设定为None则显示所有层级,设置为1,则显示最初一层 可以设置回溯层级比错误层级高的数 19 # file=sys.stdout:此为在控制台输出错误信息,file=open('log.log', mode='a', encoding='utf-8')存储于文件中
traceback.print_exception(etype,value,tb,limit = None,file = None,chain = True )
# tb打印异常信息和堆栈跟踪条目到文件。这与print_tb()以下方面有所不同: # 如果tb不是None,则打印一个标题Traceback(most recent call last): # 它将在堆栈跟踪之后打印异常etype 和 值 # 如果类型(值)是,SyntaxError并且值具有适当的格式,那么它会打印出发生语法错误的那一行,并且指出错误的大致位置。 # 可选的限制参数的含义为相同print_tb()。如果链为真(默认值),则链式异常(的cause__或__context__异常的属性)将被打印,以及像解释打印未处理的异常时本身一样。 # 改变在3.5版本:该VLAN时参数将被忽略,并从类型推断值。
import sys import traceback def lumberjack(): bright_side_of_death() def bright_side_of_death(): return print(tuple()[0]) try: lumberjack() except IndexError: exc_type, exc_value, exc_traceback = sys.exc_info() print("*** print_exception:") # exc_type below is ignored on 3.5 and later traceback.print_exception(exc_type, exc_value, exc_traceback, limit=None, file=sys.stdout) # 从左到右依次表示 错误类型,错误位置,错误最近引用的堆栈,显示错误层级,显示在控制台 # 结果: # ** *print_exception: # Traceback(most recent call last): # File"D:/pycharm/S9/pythontext/main.py", line108, in < module > # lumberjack() # File"D:/pycharm/S9/pythontext/main.py", line102, in lumberjack # bright_side_of_death() # File"D:/pycharm/S9/pythontext/main.py", line105, in bright_side_of_death # return print(tuple()[0]) # IndexError: tuple index out of range
PS:小技巧(精确定位错误代码所在行的位置方法)exc_traceback.tb_lineno
import sys import traceback def lumberjack(): bright_side_of_death() def bright_side_of_death(): return print(tuple()[0]) try: lumberjack() except IndexError: exc_type, exc_value, exc_traceback = sys.exc_info() # print(repr(traceback.format_tb(exc_traceback))) print("*** tb_lineno:", exc_traceback.tb_lineno) # 精确错误行的为止代码 # 结果: # *** tb_lineno: 108

浙公网安备 33010602011771号