欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

搞清楚 Python traceback的具體使用方法

 更新時(shí)間:2019年05月13日 14:19:55   作者:lengxingxing_  
這篇文章主要介紹了搞清楚 Python traceback的具體使用方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

1. Python中的異常棧跟蹤

之前在做Java的時(shí)候,異常對(duì)象默認(rèn)就包含stacktrace相關(guān)的信息,通過異常對(duì)象的相關(guān)方法printStackTrace()和getStackTrace()等方法就可以取到異常棧信息,能打印到log輔助調(diào)試或者做一些別的事情。但是到了Python,在2.x中,異常對(duì)象可以是任何對(duì)象,經(jīng)??吹胶芏啻a是直接raise一個(gè)字符串出來,因此就不能像Java那樣方便的獲取異常棧了,因?yàn)楫惓?duì)象和異常棧是分開的。而多數(shù)Python語言的書籍上重點(diǎn)在于描述Python中如何構(gòu)造異常對(duì)象和raise try except finally這些的使用,對(duì)調(diào)試程序起關(guān)鍵作用的stacktrace往往基本上不怎么涉及。

python中用于處理異常棧的模塊是traceback模塊,它提供了print_exception、format_exception等輸出異常棧等常用的工具函數(shù)。

def func(a, b):
 return a / b
if __name__ == '__main__':
 import sys
 import traceback
 try:
 func(1, 0)
 except Exception as e:
 print "print exc"
 traceback.print_exc(file=sys.stdout)

輸出結(jié)果:

print exc
Traceback (most recent call last):
  File "./teststacktrace.py", line 7, in <module>
    func(1, 0)
  File "./teststacktrace.py", line 2, in func
    return a / b

其實(shí)traceback.print_exc()函數(shù)只是traceback.print_exception()函數(shù)的一個(gè)簡(jiǎn)寫形式,而它們獲取異常相關(guān)的數(shù)據(jù)都是通過sys.exc_info()函數(shù)得到的。

def func(a, b):
 return a / b
if __name__ == '__main__':
 import sys
 import traceback
 try:
 func(1, 0)
 except Exception as e:
 print "print_exception()"
 exc_type, exc_value, exc_tb = sys.exc_info()
 print 'the exc type is:', exc_type
 print 'the exc value is:', exc_value
 print 'the exc tb is:', exc_tb
 traceback.print_exception(exc_type, exc_value, exc_tb)

輸出結(jié)果:

print_exception()
the exc type is: <type 'exceptions.ZeroDivisionError'>
the exc value is: integer division or modulo by zero
the exc tb is: <traceback object at 0x104e7d4d0>
Traceback (most recent call last):
  File "./teststacktrace.py", line 7, in <module>
    func(1, 0)
  File "./teststacktrace.py", line 2, in func
    return a / b
ZeroDivisionError: integer division or modulo by zero

sys.exc_info()返回的值是一個(gè)元組,其中第一個(gè)元素,exc_type是異常的對(duì)象類型,exc_value是異常的值,exc_tb是一個(gè)traceback對(duì)象,對(duì)象中包含出錯(cuò)的行數(shù)、位置等數(shù)據(jù)。然后通過print_exception函數(shù)對(duì)這些異常數(shù)據(jù)進(jìn)行整理輸出。
traceback模塊提供了extract_tb函數(shù)來更加詳細(xì)的解釋traceback對(duì)象所包含的數(shù)據(jù):

def func(a, b):
 return a / b
if __name__ == '__main__':
 import sys
 import traceback
 try:
 func(1, 0)
 except:
 _, _, exc_tb = sys.exc_info()
 for filename, linenum, funcname, source in traceback.extract_tb(exc_tb):
  print "%-23s:%s '%s' in %s()" % (filename, linenum, source, funcname)

輸出結(jié)果:

samchimac:tracebacktest samchi$ python ./teststacktrace.py
./teststacktrace.py    :7 'func(1, 0)' in <module>()
./teststacktrace.py    :2 'return a / b' in func()

2. 使用cgitb來簡(jiǎn)化異常調(diào)試

如果平時(shí)開發(fā)喜歡基于log的方式來調(diào)試,那么可能經(jīng)常去做這樣的事情,在log里面發(fā)現(xiàn)異常之后,因?yàn)樾畔⒉蛔?,那么?huì)再去額外加一些debug log來把相關(guān)變量的值輸出。調(diào)試完畢之后再把這些debug log去掉。其實(shí)沒必要這么麻煩,Python庫中提供了cgitb模塊來幫助做這些事情,它能夠輸出異常上下文所有相關(guān)變量的信息,不必每次自己再去手動(dòng)加debug log。

cgitb的使用簡(jiǎn)單的不能想象:

def func(a, b):
    return a / b
if __name__ == '__main__':
    import cgitb
    cgitb.enable(format='text')
    import sys
    import traceback
    func(1, 0)

運(yùn)行之后就會(huì)得到詳細(xì)的數(shù)據(jù):

A problem occurred in a Python script.  Here is the sequence of
function calls leading up to the error, in the order they occurred.

 /Users/samchi/Documents/workspace/tracebacktest/teststacktrace.py in <module>()
    4  import cgitb
    5  cgitb.enable(format='text')
    6  import sys
    7  import traceback
    8  func(1, 0)
func = <function func>

 /Users/samchi/Documents/workspace/tracebacktest/teststacktrace.py in func(a=1, b=0)
    2  return a / b
    3 if __name__ == '__main__':
    4  import cgitb
    5  cgitb.enable(format='text')
    6  import sys
a = 1
b = 0

完全不必再去log.debug("a=%d" % a)了,個(gè)人感覺cgitb在線上環(huán)境不適合使用,適合在開發(fā)的過程中進(jìn)行調(diào)試,非常的方便。
也許你會(huì)問,cgitb為什么會(huì)這么屌?能獲取這么詳細(xì)的出錯(cuò)信息?其實(shí)它的工作原理同它的使用方式一樣的簡(jiǎn)單,它只是覆蓋了默認(rèn)的sys.excepthook函數(shù),sys.excepthook是一個(gè)默認(rèn)的全局異常攔截器,可以嘗試去自行對(duì)它修改:

def func(a, b):
    return a / b
def my_exception_handler(exc_type, exc_value, exc_tb):
    print "i caught the exception:", exc_type
    while exc_tb:
        print "the line no:", exc_tb.tb_lineno
        print "the frame locals:", exc_tb.tb_frame.f_locals
        exc_tb = exc_tb.tb_next
 
if __name__ == '__main__':
    import sys
    sys.excepthook = my_exception_handler
    import traceback
    func(1, 0)

輸出結(jié)果:

i caught the exception: <type 'exceptions.ZeroDivisionError'>
the line no: 14
the frame locals: {'my_exception_handler': <function my_exception_handler at 0x100e04aa0>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': './teststacktrace.py', 'traceback': <module 'traceback' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/traceback.pyc'>, '__package__': None, 'sys': <module 'sys' (built-in)>, 'func': <function func at 0x100e04320>, '__name__': '__main__', '__doc__': None}
the line no: 2
the frame locals: {'a': 1, 'b': 0}

看到?jīng)]有?沒有什么神奇的東西,只是從stack frame對(duì)象中獲取的相關(guān)變量的值。frame對(duì)象中還有很多神奇的屬性,就不一一探索了。

3. 使用logging模塊來記錄異常

在使用Java的時(shí)候,用log4j記錄異常很簡(jiǎn)單,只要把Exception對(duì)象傳遞給log.error方法就可以了,但是在Python中就不行了,如果直接傳遞異常對(duì)象給log.error,那么只會(huì)在log里面出現(xiàn)一行異常對(duì)象的值。

在Python中正確的記錄Log方式應(yīng)該是這樣的:

logging.exception(ex)
logging.error(ex, exc_info=1) # 指名輸出棧蹤跡, logging.exception的內(nèi)部也是包了一層此做法
logging.critical(ex, exc_info=1) # 更加嚴(yán)重的錯(cuò)誤級(jí)別

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論