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调用c++返回带成员指针的类指针实例

这个是OK的: class Rtmp_tool { public: int m_width; AVCodecContext * c; }; 指针的用法如下: Rtm...

Python语言生成水仙花数代码示例

Python语言生成水仙花数代码示例

水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。 本文将通过Python代码实现打印水仙花数,具体如下: #水仙花数 #narcissist...

python判断一个集合是否为另一个集合的子集方法

实例如下所示: a = [1,2,3,4] b = set([1,2]) b.issubset(a) 以上这篇python判断一个集合是否为另一个集合的子集方法就是小编分享给大家的...

python模拟登录并且保持cookie的方法详解

前言 最近在爬行 nosec.org 的数据,看了下需要模拟登录拿到cookie后才能访问想抓的数据,重要的是 nosec.org 的登录页面 form 中有个 authenticit...

Python面向对象之类的封装操作示例

本文实例讲述了Python面向对象之类的封装操作。分享给大家供大家参考,具体如下: 承接上一节《Python面向对象之类和实例》,学了Student类的定义及实例化,每个实例都拥有各自的...