I read Get last function's call arguments from traceback? but it is not specific enough to answer my problem.
This is really bothering me since not having the call arguments is slowing me down and I am pretty sure that it is possible to get this kind of info from Python.
Here is an example to illustrate the problem:
# -*- 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()
so I get details, but the call arguments are not contained:
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: ()
Method 1: By using print_exc() method. This method prints exception information and stack trace entries from traceback object tb to file.
traceback. print_exc(limit = None, file = None, chain = True) : This is a shorthand for print_exception(*sys. exc_info(), limit, file, chain). traceback. print_last(limit = None, file = None, chain = True) : It works only after an exception has reached an interactive prompt.
The most common method to catch and print the exception message in Python is by using except and try statement. You can also save its error message using this method.
frames[0][0]
represents main
function. main
is called without arguments, thats why you get empty tuple. Change it to frames[-1][0]
to get last frame.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With