在Python中获取异常类名? [英] getting the exception class name in python?
问题描述
我想在一个异常处理程序中生成一个字符串,其中包含异常的名称,以及传递的任何参数……几乎是使用Traceback获得的最终输出。
I want to generate a string in an exception handler that contains the name of the exception, and any arguments passed...oretty much the final output that one gets with Traceback.
例如,如果调用 raise bar.FnordError( message)
,则在异常处理程序中,我想生成字符串: bar.FnordError:消息
For example, if raise bar.FnordError("message")
is called, in the exception handler, I want to produce the string: "bar.FnordError: message"
我希望它适用于内置的异常以及当前模块和其他模块中的异常。这是我想出的,但似乎不是很Python。
I want it to work for built in exceptions, as well as exceptions in the current and other modules. This is what I came up with, but it doesn't seem very pythonic.
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标准库进行了挖掘。我似乎缺少正确的不错的访问器。
I've dug through the BaseException C code in python, and the Traceback standard library. I seem to be missing the correct "nice" accessor.
BaseException .__ format __
是否记录在任何地方?
Is BaseException.__format__
documented anywhere? Are there escapes for it?
我在翻译中玩过,什么也没给我我想要的东西。
I've played around in the interpreter and nothing quite gives me what I want.
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'
推荐答案
没有不错的访问器。 Python本身所做的事情与您在默认的 sys.excepthook
中所做的非常相似,尽管在 __ main __
中定义了异常打印为 __ main __。WhateverException
。
There's no "nice" accessor. Python itself does something pretty similar to what you're doing in the default sys.excepthook
, although exceptions defined in __main__
print as __main__.WhateverException
.
如果您想了解Python本身是如何做到的,在Python 2上,检查发生在 PyErr_Display
,它检查 strcmp(modstr, exceptions)
:
If you want to see how Python itself does it, on Python 2, the check happens in PyErr_Display
, which checks strcmp(modstr, "exceptions")
:
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);
}
在Python 3上, print_exception
检查 _PyUnicode_CompareWithId(
On Python 3, print_exception
checks _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);
}
这篇关于在Python中获取异常类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!