python堆栈跟踪,如何在Python中获取完整的异常堆栈跟踪

The following snippet:

import traceback

def a():

b()

def b():

try:

c()

except:

traceback.print_exc()

def c():

assert False

a()

Produces this output:

Traceback (most recent call last):

File "test.py", line 8, in b

c()

File "test.py", line 13, in c

assert False

AssertionError

What should I use if I want the complete stack trace including the call to a?

If it matters I have Python 2.6.6

edit: What I'd like to get is the same information I'd get if I left the try except out and let the exception propagate to the top level. This snippet for example:

def a():

b()

def b():

c()

def c():

assert False

a()

Produces this output:

Traceback (most recent call last):

File "test.py", line 10, in

a()

File "test.py", line 2, in a

b()

File "test.py", line 5, in b

c()

File "test.py", line 8, in c

assert False

AssertionError

解决方案

I don't know if there is a better way, but here's what I did:

import traceback

import sys

def format_exception(e):

exception_list = traceback.format_stack()

exception_list = exception_list[:-2]

exception_list.extend(traceback.format_tb(sys.exc_info()[2]))

exception_list.extend(traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1]))

exception_str = "Traceback (most recent call last):\n"

exception_str += "".join(exception_list)

# Removing the last \n

exception_str = exception_str[:-1]

return exception_str

def main1():

main2()

def main2():

try:

main3()

except Exception as e:

print "Printing only the traceback above the current stack frame"

print "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]))

print

print "Printing the full traceback as if we had not caught it here..."

print format_exception(e)

def main3():

raise Exception()

if __name__ == '__main__':

main1()

And here's the output I get:

Printing only the traceback above the current stack frame

Traceback (most recent call last):

File "exc.py", line 22, in main2

main3()

File "exc.py", line 31, in main3

raise Exception()

Exception

Printing the full traceback as if we had not caught it here...

Traceback (most recent call last):

File "exc.py", line 34, in

main1()

File "exc.py", line 18, in main1

main2()

File "exc.py", line 22, in main2

main3()

File "exc.py", line 31, in main3

raise Exception()

Exception

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值