python traceback捕获并打印异常的方法

yipeiwu_com6年前Python基础

异常处理是日常操作了,但是有时候不能只能打印我们处理的结果,还需要将我们的异常打印出来,这样更直观的显示错误

下面来介绍traceback模块来进行处理

  try:
    1/0
  except Exception, e:
    print e

输出结果是integer division or modulo by zero,只知道是报了这个错,但是却不知道在哪个文件哪个函数哪一行报的错。

使用traceback

  try:
    1/0
  except Exception, e:
    traceback.print_exc()

输出结果

Traceback (most recent call last):

        File "test_traceback.py", line 3, in <module>

           1/0

ZeroDivisionError: integer division or modulo by zero

这样非常直观有利于调试。

 traceback.print_exc()跟traceback.format_exc()有什么区别呢?

format_exc()返回字符串,print_exc()则直接给打印出来。

即traceback.print_exc()与print traceback.format_exc()效果是一样的。

print_exc()还可以接受file参数直接写入到一个文件。比如

traceback.print_exc(file=open('tb.txt','w+'))

写入到tb.txt文件去。

示例

# -*- coding:utf-8 -*-

import os
import logging
import traceback

#设置log, 这里使用默认log
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    datefmt='[%Y-%m_%d %H:%M:%S]',
    filename=os.path.dirname(os.path.realpath(__file__)) + "/" + 'test.log',
    filemode='a')

a=10
b=0 #设置为0, 走异常流程; 否则, 走正常流程

try:
  res=a/b
  logging.info("exec success, res:" + str(res))
except Exception,e:
  #format_exc()返回字符串,print_exc()则直接给打印出来
  traceback.print_exc()
  logging.warning("exec failed, failed msg:" + traceback.format_exc())

logging默认打印级别是warning.

日志打印:

[2017-11_17 07:51:02] trace.py[line:24] WARNING exec failed, failed msg:Traceback (most recent call last):

  File "trace.py", line 19, in <module>

    res=a/b

ZeroDivisionError: integer division or modulo by zero

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

相关文章

Python中py文件转换成exe可执行文件的方法

Python中py文件转换成exe可执行文件的方法

一、背景 今天闲着无事,写了一个小小的Python脚本程序,然后给同学炫耀的时候,发现每次都得拉着其他人过来看着自己的电脑屏幕,感觉不是很爽,然后我想着网上肯定有关于Python脚本转...

Django框架下在URLconf中指定视图缓存的方法

将视图与缓存系统进行了耦合,从几个方面来说并不理想。 例如,你可能想在某个无缓存的站点中重用该视图函数,或者你可能想将该视图发布给那些不想通过缓存使用它们的人。 解决这些问题的方法是在...

解决python线程卡死的问题

1. top命令和日志方式判定卡死的位置 python代码忽然卡死,日志不输出,通过如下方式可以确定线程确实已经死掉了: # top 命令 top命令可以看到机器上所有线程的执行情况,%...

使用Python 统计高频字数的方法

问题 (来自Udacity机器学习工程师纳米学位预览课程) 用 Python 实现函数 count_words(),该函数输入字符串 s 和数字 n,返回 s 中 n 个出现频率最高的单...

python2.7+selenium2实现淘宝滑块自动认证功能

python2.7+selenium2实现淘宝滑块自动认证功能

本文为大家分享了python2.7+selenium2实现淘宝滑块自动认证的具体代码,供大家参考,具体内容如下 1.编译环境 操作系统:win7;语言:python2.7+selen...