max max - 4 days ago 6
Python Question

python traceback - how to raise an exception and keep the stack

I have 2 modules:

a.py:



import b
import traceback
try:
print b.get_val(1)
except Exception as ex:
traceback.print_stack()
print ex


The problem is that the stack trace does not say whick line of b.py raised the exception. It also happens if there is an actual run time error.
Any ideas how to display the whole stack?

b.py



def get_val(val):
print 'hi'
raise Exception('Bad value')

Answer

Try traceback.print_exc() instead of traceback.print_stack()

traceback.print_stack() output:

hi
  File "a.py", line 6, in <module>
    traceback.print_stack()
Bad value

traceback.print_exc() output:

hi
Traceback (most recent call last):
  File "a.py", line 4, in <module>
    print b.get_val(1)
  File "C:\Users\Ahmed\Desktop\SOF\b.py", line 3, in get_val
    raise Exception('Bad value')
Exception: Bad value
Bad value
Comments