Java e、 python中的printStackTrace等价物

Java e、 python中的printStackTrace等价物,java,python,exception,stack-trace,Java,Python,Exception,Stack Trace,我知道,print(e)(e是异常)会打印发生的异常 但是,我试图找到与Java的e.printStackTrace()相当的python,它精确地跟踪异常发生的那一行,并打印它的整个跟踪 有人能告诉我Python中的e.printStackTrace()的等价物吗 import traceback traceback.print_exc() 在除…:块内执行此操作时,它将自动使用当前异常。有关更多信息,请参阅。还有日志记录。异常 import logging ... try: g

我知道,
print(e)
(e是异常)会打印发生的异常 但是,我试图找到与Java的
e.printStackTrace()
相当的python,它精确地跟踪异常发生的那一行,并打印它的整个跟踪

有人能告诉我Python中的
e.printStackTrace()
的等价物吗

import traceback
traceback.print_exc()

除…:
块内执行此操作时,它将自动使用当前异常。有关更多信息,请参阅。

还有
日志记录。异常

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
(来自via)

e.printStackTrace在python中的等效值

在Java中,它执行以下()操作:

将此可丢弃文件及其回溯打印到标准错误流

这是这样使用的:

try
{ 
// code that may raise an error
}
catch (IOException e)
{
// exception handling
e.printStackTrace();
}
在Java中,标准错误流是无缓冲的,因此输出会立即到达。

Python 2中的相同语义包括: Python 3 在Python3中,我们可以直接从异常对象获取回溯(对于线程代码来说,异常对象可能表现得更好)。 还有,但是print函数 一个flush参数,因此它将立即打印到stderr:

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

print(traceback.format)日志记录
库的
debug()
info()
警告()
错误()
,以及
临界()
方法

kwargs中有三个被检查的关键字参数:exc_info,如果它的计算结果不为false,则会将异常信息添加到日志消息中

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

import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

def f():
    a = { 'foo': None }
    # the following line will raise KeyError
    b = a['bar']

def g():
    f()

try:
    g()
except Exception as e:
    logger.error(str(e), exc_info=True)
它将输出:

'bar'
Traceback (most recent call last):
  File "<ipython-input-2-8ae09e08766b>", line 18, in <module>
    g()
  File "<ipython-input-2-8ae09e08766b>", line 14, in g
    f()
  File "<ipython-input-2-8ae09e08766b>", line 10, in f
    b = a['bar']
KeyError: 'bar'
'bar'
回溯(最近一次呼叫最后一次):
文件“”,第18行,在
g()
文件“”,第14行,在g中
f()
文件“”,第10行,在f中
b=a['bar']
KeyError:'bar'

如果您在某种容器(例如)中工作,因此无法仅打印跟踪,您可以改为获取字符串。与
traceback.print_exc()相比,这种方法的优点/缺点是什么
?最大的优点是,您可以通过配置记录器来控制要查看的内容/位置。例如,您可以使用它将日志发送到生产中的日志记录服务,以便更容易解决难以重现的问题。
import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

def f():
    a = { 'foo': None }
    # the following line will raise KeyError
    b = a['bar']

def g():
    f()

try:
    g()
except Exception as e:
    logger.error(str(e), exc_info=True)
'bar'
Traceback (most recent call last):
  File "<ipython-input-2-8ae09e08766b>", line 18, in <module>
    g()
  File "<ipython-input-2-8ae09e08766b>", line 14, in g
    f()
  File "<ipython-input-2-8ae09e08766b>", line 10, in f
    b = a['bar']
KeyError: 'bar'