【问题标题】:Python Exception cought but stack trace printed anywaysPython 异常咳嗽,但堆栈跟踪仍然打印
【发布时间】:2018-05-09 11:31:59
【问题描述】:

我试图理解为什么堆栈跟踪会被打印事件 虽然异常被捕获。以下是不同方法的示例:

方法 1

import soco
try:
    ... code that can result with the exception...
except soco.exceptions.SoCoUPnPException as e:
    logger.warning("Exception caught. Not expecting trace")

方法 2

from soco.exceptions import SoCoUPnPException
try:
    ... code that can result with the exception...
except SoCoUPnPException as e:
    logger.warning("Exception caught. Not expecting trace")

方法 3

try:
    ... code that can result with the exception...
except Exception as e:
    logger.warning("Exception caught. Not expecting trace")

它们都导致相同的错误:

ERROR [soco.services:410] UPnP Error 701 received: Transition not available from 10.10.10.114
Traceback (most recent call last):
  File "/usr/lib/python3.5/site-packages/soco/services.py", line 408, in send_command
    self.handle_upnp_error(response.text)
  File "/usr/lib/python3.5/site-packages/soco/services.py", line 469, in handle_upnp_error
    error_xml=xml_error
soco.exceptions.SoCoUPnPException: UPnP Error 701 received: Transition not available from 10.10.10.114
WARNING [senic_hub.nuimo_app.components.sonos:180] Exception caught. Not expecting trace

我希望只打印 logger.warning("Exception caught. Not expecting trace") 部分而不是整个跟踪。

更新

删除了try/catch 语句,在这种情况下soco.exceptions.SoCoUPnPException 会被提升两次。

异常代码:https://github.com/SoCo/SoCo/blob/release-0.14/soco/exceptions.py#L22

我在这里错过了什么?

【问题讨论】:

  • except: ?
  • @Mika72 鉴于Exception caught. Not expecting trace 确实被打印出来,似乎在所有三种情况下都成功捕获了异常。也许这是一个库问题,而不是代码中处理异常的方式......

标签: python-3.x exception exception-handling


【解决方案1】:

异常被正确捕获。检查Logger 类的文档。使用它的方式会导致默认打印异常信息(如debug 部分中所述;infowarning 等级别也使用相同的行为)。

有三个关键字参数 (Python 3) 可用于调整此行为:

  • exc_info - 将异常信息添加到日志消息中
  • stack_info - 将堆栈信息添加到日志消息中仅限 Python 3
  • extra - 接受一个字典来填充用于记录事件的LogRecord__dict__

要抑制堆栈和异常信息,请尝试以下操作:

import logging
import soco

try:
    ... code that can create exception ...
except soco.exceptions.SoCoUPnPException as e:
    logger.warning("Exception caught. Not expecting trace", exc_info=False, stack_info=False)    # Remove the 'stack_info=False' for Python 2

【讨论】:

  • 不是这样,但谢谢。 stack_info 也默认为 False。真的不知道如何处理 If exc_info does not evaluate as false 的默认值(您发布的文档参考)
  • @TheMeaningfulEngineer 您使用的是 Python 2 还是 3?
  • @TheMeaningfulEngineer 不是这样吗?您是否将exc_info 设置为False?这将导致它评估为假。这意味着您需要向它传递一个值或一个表达式,从而产生一个False 值。
  • 抱歉,测试了您提出的建议。情况并非如此。然后在python 3中似乎默认为False
  • @TheMeaningfulEngineer 如果您只使用print 函数而不是logger.warning,打印输出是什么?
猜你喜欢
  • 1970-01-01
  • 2012-09-04
  • 2011-01-18
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 2014-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多