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 删除整个文本中的空格,并实现按行显示

希望以后每天写一篇博客,总结一下每天用到的基本功能,不然项目做完也就做完了,给自己留下的资料太少了。 今天需要造大量的姓名和家庭住址的数据,因此根据读取文件中现有的lastname、fi...

利用python开发app实战的方法

利用python开发app实战的方法

我很早之前就想开发一款app玩玩,无奈对java不够熟悉,之前也没有开发app的经验,因此一直耽搁了。最近想到尝试用python开发一款app,google搜索了一番后,发现确实有路可寻...

Python如何使用函数做字典的值

这篇文章主要介绍了Python如何使用函数做字典的值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 当需要用到3个及以上的if...e...

浅谈关于Python3中venv虚拟环境

浅谈关于Python3中venv虚拟环境

Python3.3以上的版本通过venv模块原生支持虚拟环境,可以代替Python之前的virtualenv。 该venv模块提供了创建轻量级“虚拟环境”,提供与系统Python的隔离支...

python实现嵌套列表平铺的两种方法

方法一:使用列表推导式 >>> vec = [[1,2,3],[4,5,6],[7,8,9]] >>> get = [num for elem i...