基于python traceback实现异常的获取与处理

yipeiwu_com6年前Python基础

这篇文章主要介绍了基于python traceback实现异常的获取与处理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1、traceback.print_exc()

2、traceback.format_exc()

3、traceback.print_exception()

简单说下这三个方法是做什么用的:

1、print_exc():是对异常栈输出

2、format_exc():是把异常栈以字符串的形式返回,print(traceback.format_exc()) 就相当于traceback.print_exc()

3、print_exception():traceback.print_exc()实现方式就是traceback.print_exception(sys.exc_info()),可以点sys.exc_info()进

去看看实现

测试代码如下:

def func(a, b):
  return a / b


if __name__ == '__main__':
  import sys
  import time
  import traceback

  try:
    func(1, 0)
  except Exception as e:
    print('***', type(e), e, '***')
    time.sleep(2)

    print("***traceback.print_exc():*** ")
    time.sleep(1)
    traceback.print_exc()
    time.sleep(2)

    print("***traceback.format_exc():*** ")
    time.sleep(1)
    print(traceback.format_exc())
    time.sleep(2)

    print("***traceback.print_exception():*** ")
    time.sleep(1)
    traceback.print_exception(*sys.exc_info())

运行结果:

*** <class 'ZeroDivisionError'> division by zero ***


***traceback.print_exc():*** 
Traceback (most recent call last):
 File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module>
  func(1, 0)
 File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func
  return a / b
ZeroDivisionError: division by zero


***traceback.format_exc():*** 
Traceback (most recent call last):
 File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module>
  func(1, 0)
 File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func
  return a / b
ZeroDivisionError: division by zero


***traceback.print_exception():*** 
Traceback (most recent call last):
 File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module>
  func(1, 0)
 File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func
  return a / b
ZeroDivisionError: division by zero

可以看出,三种方式打印结果是一样的。在开发时,做调试是很方便的。也可以把这种异常栈写入日志。

logging.exception(ex)

# 指名输出栈踪迹, logging.exception的内部也是包了一层此做法
logging.error(ex, exc_info=1) 

# 更加严重的错误级别 
logging.critical(ex, exc_info=1) 

# 我直接copy的,未尝试。有时间会试下的

python 还有一个模块叫cgitb,输出的error非常详情。

  try:
    func(1, 0)
  except Exception as e:
    import cgitb
    cgitb.enable(format='text')
    func(1, 0)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python安装官方whl包和tar.gz包的方法(推荐)

Windows环境:   安装whl包:pip install wheel    ->    pip install&n...

全面了解Python的getattr(),setattr(),delattr(),hasattr()

1. getattr()函数是Python自省的核心函数,具体使用大体如下: class A: def __init__(self): self.name = 'zhangji...

对python创建及引用动态变量名的示例讲解

实际上在python中用列表就可以实现动态变量名的管理,python中的列表中可以存储任何类型的元素: listA = [0,"str",B()] 上述列表分别存储了整数,字符串...

Anaconda下安装mysql-python的包实例

Anaconda下安装mysql-python的包实例

Anaconda下需要使用Python与MySQL数据库进行交互,所以需要import一个mysql-python的包, 但是在ipython中引用的时候发现Anaconda并没有包含该...

python基于pdfminer库提取pdf文字代码实例

安装pdfminer 库 windows 下安装pdfminer3k pip install pdfminer3k Liunx 下安装pdfminer pip install...