2016-04-28 19 views
1

私は、例外の名前と、渡された引数の名前を含む例外ハンドラに文字列を生成したいと思います... Tracebackで得られる最終出力は多くありません。例えばPythonで例外クラス名を取得していますか?

raise bar.FnordError("message")が呼び出された場合、例外ハンドラでは、私は、文字列を生成します:"bar.FnordError: message"

私はそれが現在および他のモジュールで例外に建てられた、だけでなく、例外のために仕事をしたいです。これは私が思いついたものですが、それは非常に無色に見えません。

def this_is_lame(err): 
    if type(err).__module__ in ['__main__', 'builtins']: 
     return "{}: {}".format(type(err).__name__, err) 
    else: 
     return "{}.{}: {}".format(type(err).__module__, type(err).__name__, err) 

PythonのBaseException CコードとTraceback標準ライブラリを掘り下げました。私は正しい「素敵な」アクセサを見逃しているようです。

BaseException.__format__はどこに文書化されていますか?それのためにエスケープがありますか?

私は通訳で遊んだことがあります。

生成
import sys 
import traceback 

import bar 

try: 
    raise bar.FnordError("message") 
except Exception as err: 
    print(type(err)) 
    print(repr(err)) 
    print(type(err).__module__) 
    print(type(err).__name__) 
    print(err) 
    print("this is what I want: '{}'".format(this_is_lame(err))) 

print() 

try: 
    raise ValueError("message") 
except Exception as err: 
    print(type(err)) 
    print(repr(err)) 
    print(type(err).__module__) 
    print(type(err).__name__) 
    print("this is what I want: '{}'".format(this_is_lame(err))) 

$ python foo.py 
<class 'bar.FnordError'> 
FnordError('message',) 
bar 
FnordError 
message 
this is what I want: 'bar.FnordError: message' 

<class 'ValueError'> 
ValueError('message',) 
builtins 
ValueError 
this is what I want: 'ValueError: message' 
+0

あなたのthis_is_lame_too機能は、実際にはきれいだと思います。誰かのコードを理解するのに便利です。私には良いと思われる。 – kingledion

答えて

2

のない "素敵" アクセサはありません。 Python自体は、デフォルトのsys.excepthookで行っていることとかなり似ていますが、__main__で定義されている例外は__main__.WhateverExceptionと表示されます。

あなたは、Python自体は、Python 2に、それをしない方法を確認したい場合は、チェックがstrcmp(modstr, "exceptions")をチェックする、PyErr_Displayで起こる:

のPython 3で
moduleName = PyObject_GetAttrString(exception, "__module__"); 
if (moduleName == NULL) 
    err = PyFile_WriteString("<unknown>", f); 
else { 
    char* modstr = PyString_AsString(moduleName); 
    if (modstr && strcmp(modstr, "exceptions")) 
    { 
     err = PyFile_WriteString(modstr, f); 
     err += PyFile_WriteString(".", f); 
    } 
    Py_DECREF(moduleName); 
} 

print_exceptionチェック_PyUnicode_CompareWithId(moduleName, &PyId_builtins)

moduleName = _PyObject_GetAttrId(type, &PyId___module__); 
if (moduleName == NULL || !PyUnicode_Check(moduleName)) 
{ 
    Py_XDECREF(moduleName); 
    err = PyFile_WriteString("<unknown>", f); 
} 
else { 
    if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0) 
    { 
     err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW); 
     err += PyFile_WriteString(".", f); 
    } 
    Py_DECREF(moduleName); 
} 
関連する問題