ethon中的e.printStackTrace等价物

时间:2012-03-04 13:13:23

标签: java python exception stack-trace

我知道print(e)(其中e是异常)打印发生的异常 但是,我试图找到相当于Java的e.printStackTrace()的python,它正好跟踪它发生的行的异常并打印出它的整个痕迹。

有人可以告诉我相当于Python中的e.printStackTrace()吗?

4 个答案:

答案 0 :(得分:255)

import traceback
traceback.print_exc()

except ...:块内执行此操作时,它将自动使用当前异常。有关详细信息,请参阅http://docs.python.org/library/traceback.html

答案 1 :(得分:103)

还有logging.exception

import logging

...

try:
    g()
except Exception as ex:
    logging.exception("Something awful happened!")
    # will print this message followed by traceback

输出:

ERROR 2007-09-18 23:30:19,913 error 1294 Something awful happened!
Traceback (most recent call last):
  File "b.py", line 22, in f
    g()
  File "b.py", line 14, in g
    1/0
ZeroDivisionError: integer division or modulo by zero

(从http://blog.tplus1.com/index.php/2007/09/28/the-python-logging-module-is-much-better-than-print-statements/How to print the full traceback without halting the program?

答案 2 :(得分:15)

  

e.printStackTrace等效于python

在Java中,这会执行以下操作(docs):

public void printStackTrace()
     

将此throwable及其回溯打印到标准错误流...

这是这样使用的:

try
{ 
// code that may raise an error
}
catch (IOException e)
{
// exception handling
e.printStackTrace();
}

在Java中,标准错误流是无缓冲的,因此输出会立即到达。

Python 2中的语义相同:

import traceback
import sys
try: # code that may raise an error
    pass 
except IOError as e: # exception handling
    # in Python 2, stderr is also unbuffered
    print >> sys.stderr, traceback.format_exc()
    # in Python 2, you can also from __future__ import print_function
    print(traceback.format_exc(), file=sys.stderr)
    # or as the top answer here demonstrates, use:
    traceback.print_exc()
    # which also uses stderr.

Python 3

在Python 3中,我们可以直接从异常对象获取回溯(这对于线程代码来说可能表现得更好)。 此外,stderr is line-buffered,但打印功能得到 一个flush参数,所以这会立即打印到stderr:

    print(traceback.format_exception(None, # <- type(e) by docs, but ignored 
                                     e, e.__traceback__),
          file=sys.stderr, flush=True)

<强>结论:

因此,在Python 3中,traceback.print_exc()虽然使用sys.stderr by default,但会缓冲输出,您可能会丢失它。因此,要在Python 3中获得尽可能相同的语义,请将printflush=True一起使用。

答案 3 :(得分:0)

除了其他出色的答案之外,我们还可以使用Python let rand = System.Random() let shuffle (rand : System.Random)(array :int[] ) = let rng = new Random() let mutable n = array.Length while (n > 1) do let k = rng.Next(n) n <- n - 1 let temp = array.[n] array.[n] <- array.[k] array.[k] <- temp array let playsarray = shuffle rand let scrambledarray = Array.map (fun x -> playsarray x ) let playsarra = fun (array : int[]) -> array |> playsarray let smallarray = [1..10].ToArray() let megaarray = Array.create 10 smallarray let megarrayscrambled = megaarray |> scrambledarray megarrayscrambled |> Seq.iter (fun y -> printfn "Ar: %A" y) 库的loggingdebug()info()warning()和{{1} } 方法。在文档中引用Python 3.7.4

  

在kwargs中检查了三个关键字参数:exc_info,如果不将其评估为false,则会导致将异常信息添加到日志消息中。

这意味着,您可以使用Python error()库输出critical()或其他类型的消息,而logging库将在其输出中包括堆栈跟踪。考虑到这一点,我们可以执行以下操作:

debug()

它将输出:

logging