【问题标题】:e.printStackTrace equivalent in pythonpython中的e.printStackTrace等价物
【发布时间】:2012-03-22 05:53:06
【问题描述】:

我知道print(e)(其中 e 是异常)打印发生的异常 但是,我试图找到与 Java 的 e.printStackTrace() 等效的 python,它准确地跟踪异常到它发生的行并打印它的整个跟踪。

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

【问题讨论】:

    标签: java python exception stack-trace


    【解决方案1】:
    import traceback
    traceback.print_exc()
    

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

    【讨论】:

    • 如果您在某种容器中工作,例如Jython,因此不能只打印跟踪,您可以使用format_exc 来获取字符串。
    【解决方案2】:

    还有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?

    【讨论】:

    • traceback.print_exc()相比有什么优点/缺点?
    • 最大的好处是你可以通过配置你的记录器来控制你想看到什么/在哪里。例如,您可以使用它将日志发送到生产环境中的日志服务,以便更轻松地修复难以重现的问题。
    【解决方案3】:

    python 中的 e.printStackTrace 等效项

    在 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

    【讨论】:

      【解决方案4】:

      除了其他出色的答案之外,我们还可以使用 Python logging 库的 debug()info()warning()error()critical() 方法。引用Python 3.7.4 的文档,

      在 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'
      

      【讨论】:

      • logger.error(str(e), exc_info=True) 可以更好地表达为logger.exception()
      猜你喜欢
      • 2018-09-06
      • 2013-02-06
      • 2016-12-27
      • 2013-12-13
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多