带有颜色的python raise KeyError消息

带有颜色的python raise KeyError消息,python,exception,keyerror,Python,Exception,Keyerror,似乎KeyError消息的管理方式与其他错误不同。 例如,如果我想使用颜色,它将适用于索引器,但也不适用于键错误: err_message = '\x1b[31m ERROR \x1b[0m' print err_message raise IndexError(err_message) raise KeyError(err_message) 知道为什么吗? 有没有办法绕过它? (我真的需要引发一个类型为KeyError的异常,以便以后能够捕获它)这些异常的行为是不同的。KeyError

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

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

print err_message

raise IndexError(err_message)

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

这些异常的行为是不同的。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 comment是更好的解决方案。

您是否考虑过使用日志记录和对日志输出着色,而不是尝试对错误消息着色?感谢您提供了这一伟大的解决方案!它做的工作!我将使用它而不是使用日志记录。。。对我来说似乎更容易!