[英]python raise KeyError message with color
It seems that KeyError
messages are not managed the same way the other errors are. 似乎KeyError
消息的管理方式与其他错误的管理方式不同。 For example if I want to use colors, it will work for an IndexError
but nor for a KeyError
: 例如,如果我想使用颜色,它将适用于IndexError
但也适用于KeyError
:
err_message = '\x1b[31m ERROR \x1b[0m'
print err_message
raise IndexError(err_message)
raise KeyError(err_message)
Any idea why? 知道为什么吗? And is there a way to bypass it? 有没有办法绕过它? (I really need a exception of type KeyError
to be raised, to be able to catch it later) (我真的需要引发KeyError
类型的异常,以便以后能够捕获它)
These Exceptions' behavior are different. 这些例外的行为是不同的。 KeyError does following action with message passed 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__().
One can use following workaround for this: Create own class with repr overrided: 可以使用以下解决方法:使用repr覆盖创建自己的类:
for example 例如
class X(str):
def __repr__(self):
return "'%s'" % self
raise KeyError(X('\x1b[31m ERROR \x1b[0m'))
but I realy don't understand Why this can be needed... I think @BorrajaX comment is better solution. 但我真的不明白为什么这可能需要......我认为@BorrajaX评论是更好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.