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

yipeiwu_com6年前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机器学习理论与实战(五)支持向量机

python机器学习理论与实战(五)支持向量机

       做机器学习的一定对支持向量机(support vector machine-SVM)颇为熟悉,因为在深...

Python+selenium点击网页上指定坐标的实例

Python+selenium点击网页上指定坐标的实例

例如有些页面元素很难获取,但是位置很固定,那么可以直接用坐标来进行操作 例如要对页面上的(x:200, y:100)进行操作,可以用如下代码: from selenium impor...

对于Python深浅拷贝的理解

对于Python深浅拷贝的理解

1,浅拷贝是什么? 浅拷贝是对于一个对象的顶层拷贝,通俗的理解是:拷贝了引用,并没有拷贝内容 通过a=b这种方式赋值只是赋值的引用(内存地址),a和b都指向了同一个内存空间,所...

pygame实现烟雨蒙蒙下彩虹雨

pygame实现烟雨蒙蒙下彩虹雨

学习了一天的深度学习,略有疲惫,我们用pygame搞个小游戏放松放松吧。今天我们的游戏主体是烟雨蒙蒙下彩虹雨,仿佛置身江南水乡。 游戏描述 我们希望看到江南水乡下起彩虹雨。这里背景是江南...

Django 添加静态文件的两种实现方法(必看篇)

Django添加静态文件有两种方法: 首先setting.py配置文件中添加静态文件的路径: STATICFILES_DIRS = [ os.path.join(BASE_DIR, "s...