14

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.

4
  • Python would have to store these past values whenever it calls a function, so I don't think so. If you're just trying to debug then use a real debugger or log the values. May 19, 2011 at 16:30
  • 1
    @Jochen: I think Python does store the values, since the traceback references the frame, so the frame is not garbage collected. May 19, 2011 at 16:32
  • @Jochen: I'm not trying to debug. I just want to put this information in log. To have more info about that what I need to debug.
    – Adam
    May 19, 2011 at 16:54
  • @Adam Please post your solution as an answer, don't include it in the question. I've removed it, but you can access it in the revision history: stackoverflow.com/posts/6061744/revisions
    – BartoszKP
    May 4, 2015 at 13:23

2 Answers 2

14

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.

10

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)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.