python traceback - 如何引发异常并保持堆栈

时间:2016-11-28 21:16:51

标签: python stack-trace

我有2个模块:

a.py:

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

问题是堆栈跟踪没有说明b.py引发异常。如果存在实际运行时错误,也会发生这种情况。 任何想法如何显示整个堆栈?

b.py

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

1 个答案:

答案 0 :(得分:2)

尝试使用traceback.print_exc()代替traceback.print_stack()

traceback.print_stack()输出:

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

traceback.print_exc()输出:

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