【问题标题】:java's printStackTrace() equivalent in python [duplicate]python中java的printStackTrace()等价物[重复]
【发布时间】:2011-12-15 14:52:02
【问题描述】:

在python except 块中,我想打印错误消息但我不希望程序停止执行,我知道我必须做这样的事情

try:
    1/0
except: 
    print errorMessage

在 except 部分,我希望添加类似 java 的 printStackTrace()

【问题讨论】:

标签: java python


【解决方案1】:

您还可以使用来自logging 模块的logging.exception。它将当前异常的堆栈跟踪打印到默认记录器中,作为严重性为ERROR 的消息。

链接:http://docs.python.org/2/library/logging.html#logging.Logger.exception

【讨论】:

    【解决方案2】:

    如果您真的只想要错误消息,您可以只打印错误(注意我是如何在 except 中指定异常的——这是一种很好的做法,有关捕获错误的建议,请参阅 pep8):

    try:
        1/0
    except Exception as e:
        print e
    

    但是,如果您想要堆栈跟踪,正如@Eddified 在评论中所说,您可以使用this answer 中的示例。或者更具体地针对您的情况:

    import traceback
    try:
        1/0
    except Exception as e:
        print e
        traceback.print_stack()
    

    【讨论】:

    【解决方案3】:

    看看traceback.print_exc()traceback 模块的其余部分。

    import traceback
    
    try:
        1/0
    except:
        print '>>> traceback <<<'
        traceback.print_exc()
        print '>>> end of traceback <<<'
    

    还有一些例子towards the end of the traceback documentation page

    【讨论】:

      猜你喜欢
      • 2012-05-19
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 2011-03-15
      • 2011-06-16
      • 1970-01-01
      相关资源
      最近更新 更多