How to get value of arguments passed to functions on the stack?

霸气de小男生 提交于 2019-12-30 07:59:11

问题


Using:

traceback.print_stack()

I can get:

  File "x.py", line 20, in <module>
    y(x)
  File "x.py", line 11, in y
    fun(x)
  File "x.py", line 8, in fun
    traceback.print_stack()

I there any way to get something like this:

  File "x.py", line 20, in <module>
    y(x) WHERE x == 1
  File "x.py", line 11, in y
    fun(x) WHERE x == 'str'
  File "x.py", line 8, in fun
    traceback.print_stack()

I just want to see what arguments was passed to functions.


回答1:


You can probably rig something up by using inspect.getargvalues() and accessing the stack frame belonging to your traceback:

 inspect.getargvalues(traceback.tb_frame)

You'll have to do some work to get the output exactly as desired. The above line is only for the innermost frame, so you'll have to walk up the stack and access the information you need for every frame. inspect.getouterframes() might come in handy.




回答2:


You can use the inspect module for this:

>>> import inspect
... def fn(x):
...     try:
...         print(1/0)
...     except ZeroDivisionError as e:
...         frames = inspect.trace()
...         argvalues = inspect.getargvalues(frames[0][0])
...         print("Argvalues: ", inspect.formatargvalues(*argvalues))
>>> fn(12)
Argvalues:  (x=12)


来源:https://stackoverflow.com/questions/6061744/how-to-get-value-of-arguments-passed-to-functions-on-the-stack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!