Python : trackback

Internal types

  • Code objects

Code objects represent byte-compiled executable Python code, or bytecode. The difference between a code object and a function object is that the function object contains an explicit reference to the function’s globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time). Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects.

  • Special read-only attributes: co_name gives the function name; co_argcount is the number of positional arguments (including arguments with default values); co_nlocals is the number of local variables used by the function (including arguments); co_varnames
    is a tuple containing the names of the local variables (starting with the argument names); co_cellvars is a tuple containing the names of local variables that are referenced by nested functions; co_freevars is a tuple containing the names of free variables; co_code is a string representing the sequence of bytecode instructions; co_consts is a tuple containing the literals used by the bytecode; co_names is a tuple containing the names used by the bytecode; co_filename is the filename from which the code was compiled; co_firstlineno is the first line number of the function; co_lnotab is a string encoding the mapping from bytecode offsets to line numbers (for details see the source code of the interpreter); co_stacksize is the required stack size (including local variables); co_flags is an integer encoding a number of flags for the interpreter.
  • frame object

Frame objects represent execution frames. They may occur in traceback objects .

  • Special read-only attributes: f_back is to the previous stack frame (towards the caller), or None if this is the bottom stack frame; f_code is the code object being executed in this frame; f_locals is the dictionary used to look up local variables; f_globals is used for global variables; f_builtins is used for built-in (intrinsic) names; f_lasti gives the precise instruction (this is an index into the bytecode string of the code object).
  • Special writable attributes: f_trace, if not None, is a function called at the start of each source code line (this is used by the debugger); f_lineno is the current line number of the frame — writing to this from within a trace function jumps to the given line (only for the bottom-most frame). A debugger can implement a Jump command (aka Set Next Statement) by writing to f_lineno.
  • trackback object

Traceback objects represent a stack trace of an exception. A traceback object is created when an exception occurs. When the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. When an exception handler is entered, the stack trace is made available to the program. It is accessible as the third item of the tuple returned by sys.exc_info(). When the program contains no suitable handler, the stack trace is written (nicely formatted) to the standard error stream; if the interpreter is interactive, it is also made available to the user as sys.last_traceback.

  • Special read-only attributes: tb_next is the next level in the stack trace (towards the frame where the exception occurred), or None
    if there is no next level; tb_frame points to the execution frame of the current level; tb_lineno gives the line number where the exception occurred; tb_lasti indicates the precise instruction. The line number and last instruction in the traceback may differ from the line number of its frame object if the exception occurred in a try statement with no matching except clause or with a finally clause.

traceback module

  • traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True)
import sys
import traceback

def func(a, b):
        return a/b

if __name__ == '__main__':
        try:
                func(1, 0)
        except Exception as exc:
                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)

its output:

print exception: 
('the exc type is: ', <type 'exceptions.ZeroDivisionError'>)
('the exc value is: ', ZeroDivisionError('integer division or modulo by zero',))
('the exc tb is: ', <traceback object at 0x7fe4eb246c20>)
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    func(1, 0)
  File "test.py", line 5, in func
    return a/b
ZeroDivisionError: integer division or modulo by zero
  • traceback.extract_tb(tb, limit=None)

Return a list of “pre-processed” stack trace entries extracted from the traceback object tb. It is useful for alternate formatting of stack traces. A “pre-processed” stack trace entry is a 4-tuple (filename, line number, function name, text) representing the information that is usually printed for a stack trace. The text is a string with leading and trailing whitespace stripped; if the source is not available it is None.

import sys
import traceback

def func(a, b):
        return a/b

if __name__ == '__main__':
        try:
                func(1, 0)
        except Exception as exc:
                _, _, exc_tb = sys.exc_info()
                for filename, linenum, funcname, source in traceback.extract_tb(exc_tb):
                        print('{0}\t:{1} "{2}" in {3}'.format(filename, linenum, source, funcname))

its output

test.py :9 "func(1, 0)" in <module>
test.py :5 "return a/b" in func
  • sys.excepthook(type, value, traceback)

This function prints out a given traceback and exception to sys.stderr.

  • When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook.
import sys
import traceback

def func(a, b):
        return a/b

def my_exception_handle(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__':
        sys.excepthook = my_exception_handle
        func(1, 0)

its output

i caught the exception:  <class 'ZeroDivisionError'>
the line no.:  16
the frame locals:  {'func': <function func at 0x7f5e351cebf8>, '__spec__': None, 'traceback': <module 'traceback' from '/usr/lib/python3.4/traceback.py'>, '__file__': 'test.py', 'sys': <module 'sys' (built-in)>, '__cached__': None, '__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__package__': None, '__loader__': <_frozen_importlib.SourceFileLoader object at 0x7f5e350de8d0>, 'my_exception_handle': <function my_exception_handle at 0x7f5e33812a60>}
the line no.:  5
the frame locals:  {'a': 1, 'b': 0}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,590评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,808评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,151评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,779评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,773评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,656评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,022评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,678评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,038评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,756评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,411评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,005评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,973评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,053评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,495评论 2 343

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,364评论 0 23
  • 【0分】不会唱歌 代表人物:杨幂、孟非。 【5分】尝试用气息唱歌,但不集中,并且没有音准。 代表人物:阿信、韩庚、...
    热血小土豆阅读 234评论 0 0
  • 金鸟独林,环木而鸣,清净长悠, 牧童伴笛,随风和寡,莫若独留。 翔于穹间,紫羽金翅,宛若星流, 禽鸟喳喳,视其华丽...
    暮规啼阅读 312评论 0 0
  • 白岩松曾说,人们号称最幸福的岁月其实往往是最痛苦的,只不过回忆起来非常美好。 你最幸福的岁月是什么时候?或者说你现...
    玥先森阅读 799评论 4 4
  • 1,事业永远第一 虽然金钱不是万能的,但没有钱是万万不能的,虽然这句话很俗,但绝对有道理,所以30岁之前,请把你大...
    范范_1b5d阅读 307评论 0 1