Python 异常咳嗽,但无论如何都打印了堆栈跟踪



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

方法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

我在这里错过了什么?

异常被正确捕获。查看记录器类的文档。以您拥有的方式使用它会导致默认情况下打印异常信息(如调试部分所述;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

最新更新