python traceback_Python traceback模块

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

# if str(123) > 5:

# TypeError: '>' not supported between instances of 'str' and 'int'

类似在没有try……except之前,出现异常解释器报错形式。此报错信息也可以直接存储在文件中!import traceback # 调用traceback模块1

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调用堆栈封装在最初发生异常的地方import sys

try:

if str(123) > 5:

print('这是一个无法执行的错误')

except Exception:

exc_type, exc_value, exc_traceback = sys.exc_info()

print('以下为代码错误信息:')

print('exc_type(异常类型): {}\nexc_value(异常错误的信息): {}\nexc_traceback(调用堆栈封装在最初发生异常的地方): {}'.format(exc_type, exc_value, exc_traceback))

# 控制台输出结果

# 以下为代码错误信息:

# exc_type(异常类型):

# exc_value(异常错误的信息): '>' not supported between instances of 'str' and 'int'

# exc_traceback(调用堆栈封装在最初发生异常的地方):

traceback.print_tb格式化输出错误

import sys

import traceback

# 以下是两个函数嵌套

def lumberjack():

bright_side_of_death()

def bright_side_of_death():

return tuple()[0]

# 以下是异常处理

try:

lumberjack()

except IndexError:

exc_type, exc_value, exc_traceback = sys.exc_info() # 分别接收sys.exc_info的三个元素

print("*** print_tb:的使用")

traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)

traceback.print_tb(exc_traceback, limit=None, file=open('log.log', mode='a', encoding='utf-8'))

# exc_traceback 调用堆栈封装在最初发生异常的地方

# limit= 此处显示需要显示的回溯的层级,设定为None则显示所有层级,设置为1,则显示最初一层 可以设置回溯层级比错误层级高的数

# 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:小技巧(精确定位错误代码所在行的位置方法)

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

7af40ad162d9f2d37692244a8ce521156227cca7.jpeg?token=35a30b2e1d55819c67b498ef4c303ac6

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值