Python中捕捉详细异常信息的代码示例

yipeiwu_com5年前Python基础

大家在开发的过程中可能时常碰到一个需求,需要把Python的异常信息输出到日志文件中。
网上的办法都不太实用,下面介绍一种实用的,从Python 2.7源码中扣出来的。
废话不说 直接上代码,代码不多,注释比较多而已。

import sys, traceback

traceback_template = '''Traceback (most recent call last):
 File "%(filename)s", line %(lineno)s, in %(name)s
%(type)s: %(message)s\n''' # Skipping the "actual line" item

# Also note: we don't walk all the way through the frame stack in this example
# see hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l280
# (Imagine if the 1/0, below, were replaced by a call to test() which did 1/0.)

try:
  1/0
except:
  # http://docs.python.org/2/library/sys.html#sys.exc_info
  exc_type, exc_value, exc_traceback = sys.exc_info() # most recent (if any) by default

  '''
  Reason this _can_ be bad: If an (unhandled) exception happens AFTER this,
  or if we do not delete the labels on (not much) older versions of Py, the
  reference we created can linger.

  traceback.format_exc/print_exc do this very thing, BUT note this creates a
  temp scope within the function.
  '''

  traceback_details = {
             'filename': exc_traceback.tb_frame.f_code.co_filename,
             'lineno' : exc_traceback.tb_lineno,
             'name'  : exc_traceback.tb_frame.f_code.co_name,
             'type'  : exc_type.__name__,
             'message' : exc_value.message, # or see traceback._some_str()
            }

  del(exc_type, exc_value, exc_traceback) # So we don't leave our local labels/objects dangling
  # This still isn't "completely safe", though!
  # "Best (recommended) practice: replace all exc_type, exc_value, exc_traceback
  # with sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]


  ## 修改这里就可以把traceback打到任意地方,或者存储到文件中了
  print traceback_template % traceback_details

相关文章

详解python中的hashlib模块的使用

hashlib hashlib主要提供字符加密功能,将md5和sha模块整合到了一起,支持md5,sha1, sha224, sha256, sha384, sha512等算法 hash...

opencv python 图像去噪的实现方法

opencv python 图像去噪的实现方法

在早先的章节里,我们看到很多图像平滑技术如高斯模糊,Median模糊等,它们在移除数量小的噪音时在某种程度上比较好用。在这些技术里,我们取像素周围的一小部分邻居,做一些类似于高斯平均权重...

使用Python实现图像标记点的坐标输出功能

使用Python实现图像标记点的坐标输出功能

Sometimes we have need to interact  with an application,for example by marking points in...

Python面向对象基础入门之设置对象属性

前言 前面我们已经介绍了 python面向对象入门教程之从代码复用开始(一) ,这篇文章主要介绍的是关于Python面向对象之设置对象属性的相关内容,下面话不多说了,来一起看看...

Java与Python两大幸存者谁更胜一筹呢

Java与Python两大幸存者谁更胜一筹呢

在学习编程语言上,相信很多人都纠结过学哪种语言更好?其实,在选择是更多的时候我们更多是需要看自己更适合。本篇文章,千锋武汉小编与大家共同讨论的编程语言,或许更多的是限于python和Ja...