简体   繁体   English

Python异常:如何打印堆栈跟踪的最后十行?

[英]Python exception: how to print the last ten lines of stack trace?

In Python as many other languages, the default behavior of an uncaught exception is to print a full stack trace.在 Python 和许多其他语言中,未捕获异常的默认行为是打印完整的堆栈跟踪。 This is useful except that hundreds of lines of stack trace obscure previous console output with data most of which is uninformative.这很有用,除了数百行堆栈跟踪用数据掩盖了以前的控制台输出,其中大部分是无信息的。 I really just want to see maybe the last ten lines of the stack trace.我真的只想看看堆栈跟踪的最后十行。

What code can go into an exception handler to print a stack trace just the way it would happen with an uncaught exception, except only print the last ten lines?什么代码可以进入异常处理程序来打印堆栈跟踪,就像未捕获的异常一样,除了只打印最后十行?

Try this:尝试这个:

# import trace back module and get stack trace
import traceback 
try:
  statement
except:
  error = traceback.format_exc()

# split stack trace into a list and slice it
stack_trace = error.split('\n')
stack_trace[len(stack_trace)-10:len(stack_trace)+1]

sys.excepthook lets you specify a function to print out to stderr and use traceback.format_tb to parse the traceback. sys.excepthook允许您指定一个函数以打印到stderr并使用traceback.format_tb来解析回溯。 The benefit being here you don't have to catch the error from a try ... except .在这里的好处是,您不必从try ... except捕获错误try ... except .

import sys
import traceback as tb

def except_hook(type, value, traceback):
    lines = 10
    tb_lines = "".join(tb.format_tb(traceback)).split("\n")
    print("\n".join(tb_lines[-lines:] + [repr(value)]), file=sys.stderr)

sys.excepthook = except_hook

def a(x):
    return b(x)

def b(x):
    return c(x)

def c(x):
    return d(x)

def d(x):
    return x / 0

a(5)

Which produces:其中产生:

~ python err.py
    a(5)
  File "err.py", line 12, in a
    return b(x)
  File "err.py", line 15, in b
    return c(x)
  File "err.py", line 18, in c
    return d(x)
  File "err.py", line 21, in d
    return x / 0

ZeroDivisionError('division by zero')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM