【问题标题】:python raise KeyError message with colorpython用颜色引发KeyError消息
【发布时间】:2013-06-25 09:14:58
【问题描述】:

似乎KeyError 消息的管理方式与其他错误不同。 例如,如果我想使用颜色,它适用于IndexError,但不适用于KeyError

err_message = '\x1b[31m ERROR \x1b[0m'

print err_message

raise IndexError(err_message)

raise KeyError(err_message)

知道为什么吗? 有没有办法绕过它? (我真的需要引发 KeyError 类型的异常,以便以后能够捕获它)

【问题讨论】:

标签: python exception keyerror


【解决方案1】:

这些异常的行为是不同的。 KeyError 执行以下操作并传递消息

   If args is a tuple of exactly one item, apply repr to args[0].
   This is done so that e.g. the exception raised by {}[''] prints
     KeyError: ''
   rather than the confusing
     KeyError
   alone.  The downside is that if KeyError is raised with an explanatory
   string, that string will be displayed in quotes.  Too bad.
   If args is anything else, use the default BaseException__str__().

为此,可以使用以下解决方法: 创建自己的类并覆盖 repr

例如

class X(str):
    def __repr__(self):
        return "'%s'" % self

raise KeyError(X('\x1b[31m ERROR \x1b[0m'))

但我真的不明白为什么需要这个... 我认为@BorrajaX 评论是更好的解决方案。

【讨论】:

  • 感谢这个伟大的解决方法!它完成了工作!我会这样做而不是使用日志记录......在我的情况下似乎更容易!
猜你喜欢
  • 1970-01-01
  • 2011-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 2018-04-04
相关资源
最近更新 更多