簡體   English   中英

從traceback獲取最后一個函數的參數?

[英]Get last function's arguments from traceback?

從traceback讀取Get last函數的調用參數? 但它不足以回答我的問題。

這真的很困擾我,因為沒有調用參數會減慢我的速度,我很確定可以從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: ()

frames[0][0]表示main功能。 main被稱為不帶參數,這就是為什么你得到空元組。 將其更改為frames[-1][0]以獲取最后一幀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM