2013-06-27 42 views
6

KeyErrorメッセージは他のエラーと同じように管理されていないようです。私は色を使用したい場合は、それがIndexErrorのために働くが、もKeyErrorためだろうたとえば :python raise KeyError message with color

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

print err_message 

raise IndexError(err_message) 

raise KeyError(err_message) 

任意のアイデアなぜですか? それをバイパスする方法はありますか? (後でキャッチできるように、実際にはKeyError型の例外が必要です)

+2

エラーメッセージを色づけしようとするよりも、ロギングの出力を色分けすることを検討しましたか? http://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output – BorrajaX

答えて

4

これらの例外の動作は異なります。 「は、例えば

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

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

を私は本当にドン: はのreprをオーバーライドして独自のクラスを作成します。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__(). 

一つは、このために、以下の回避策を使用することができますが渡されたメッセージとアクションを以下のんなぜこれが必要なのか理解しています... @BorrajaXのコメントは良い解決策だと思います。

+0

この素晴らしい回避策に感謝します! それは仕事をする! ロギングを使用する代わりに、そのために行くつもりです...私の場合は簡単です! –