从traceback获取最后一个函数的参数?

时间:2016-10-22 10:21:12

标签: python exception stack-trace

我看过Get last function's call arguments from traceback?,但它不够具体,无法回答我的问题。

这真的让我感到困扰,因为没有调用参数会减慢我的速度,我很确定可以从Python中获取这种信息。

以下是一个说明问题的示例:

# -*- coding: utf-8 -*-
import sys
import traceback
import inspect
import logging as log

def fl(x):
    # exception is happening here
    y = 5/x
    return y


def fm(x):
    return fl(x-3)


def fn(a, b, c=None):
    return fm(c)


def main():

    try:
        print fn(1, 2, c=3)
    except Exception as e:
        log.error('Unexpected problem.')
        log.error(e)
        traceback.print_exc()
        ### what I need to see is are the call arguments of the last / deepest call: ###
        ### def fl(x) was called with arguments: [(x, 3)]                            ###
        # this does not cut it:
        tb = sys.exc_info()[2]
        traceback.print_tb(tb)
        # this is broken:
        #frames = inspect.getinnerframes(tb)
        #log.error('Argvalues: %s', inspect.getargvalues(frames))
        # not sure:
        frames = inspect.trace()
        argvalues = inspect.getargvalues(frames[0][0])
        log.error('Argvalues: %s', inspect.formatargvalues(*argvalues))



if __name__ == '__main__':
    main()

所以我得到了详细信息,但调用参数未包含在内:

ERROR:root:Unexpected problem.
ERROR:root:integer division or modulo by zero
Traceback (most recent call last):
  File "sample.py", line 24, in main
    print fn(1, 2, c=3)
  File "sample.py", line 18, in fn
    return fm(c)
  File "sample.py", line 14, in fm
    return fl(x-3)
  File "sample.py", line 9, in fl
    y = 5/x
ZeroDivisionError: integer division or modulo by zero
  File "sample.py", line 24, in main
    print fn(1, 2, c=3)
  File "sample.py", line 18, in fn
    return fm(c)
  File "sample.py", line 14, in fm
    return fl(x-3)
  File "sample.py", line 9, in fl
    y = 5/x
ERROR:root:Argvalues: ()

1 个答案:

答案 0 :(得分:1)

frames[0][0]代表main功能。调用main时不带参数,这就是为什么你得到空元组。将其更改为frames[-1][0]以获取最后一帧。