打印Python异常/错误层次结构

时间:2013-08-18 07:16:35

标签: python class exception

python中的any命令行选项是否打印Exception / Error Class层次结构?

输出应类似于http://docs.python.org/2/library/exceptions.html#exception-hierarchy

2 个答案:

答案 0 :(得分:25)

inspect模块可能有所帮助,特别是getclasstree()功能:

  

将给定的类列表排列为嵌套列表的层次结构。   在出现嵌套列表的地方,它包含从中派生的类   其条目紧接在列表之前的类。

inspect.getclasstree(inspect.getmro(Exception))

或者,您可以递归地通过继承树递归__subclasses__(),如下所示:

def classtree(cls, indent=0):
    print '.' * indent, cls.__name__
    for subcls in cls.__subclasses__():
        classtree(subcls, indent + 3)

classtree(BaseException)

打印:

 BaseException
... Exception
...... StandardError
......... TypeError
......... ImportError
............ ZipImportError
......... EnvironmentError
............ IOError
............... ItimerError
............ OSError
......... EOFError
......... RuntimeError
............ NotImplementedError
......... NameError
............ UnboundLocalError
......... AttributeError
......... SyntaxError
............ IndentationError
............... TabError
......... LookupError
............ IndexError
............ KeyError
............ CodecRegistryError
......... ValueError
............ UnicodeError
............... UnicodeEncodeError
............... UnicodeDecodeError
............... UnicodeTranslateError
......... AssertionError
......... ArithmeticError
............ FloatingPointError
............ OverflowError
............ ZeroDivisionError
......... SystemError
............ CodecRegistryError
......... ReferenceError
......... MemoryError
......... BufferError
...... StopIteration
...... Warning
......... UserWarning
......... DeprecationWarning
......... PendingDeprecationWarning
......... SyntaxWarning
......... RuntimeWarning
......... FutureWarning
......... ImportWarning
......... UnicodeWarning
......... BytesWarning
...... _OptionError
... GeneratorExit
... SystemExit
... KeyboardInterrupt

答案 1 :(得分:0)

重用标准库中的代码,而不是自己编写代码。

import inspect
import pydoc

def print_class_hierarchy(classes=()):
    td = pydoc.TextDoc()
    tree_list_of_lists = inspect.getclasstree(classes)
    print(td.formattree(tree_list_of_lists, 'NameSpaceName'))

要使用它,我们需要以列表形式的类层次结构,这对我们传递函数是有意义的。我们可以通过使用此函数(which I'll keep the canonical version of here)递归搜索类.__subclasses__()方法结果来构建它:

def get_subclasses(cls):
    """returns all subclasses of argument, cls"""
    if issubclass(cls, type): # not a bound method
        subclasses = cls.__subclasses__(cls)
    else:
        subclasses = cls.__subclasses__()
    for subclass in subclasses:
        subclasses.extend(get_subclasses(subclass))
    return subclasses

把它放在一起:

list_of_classes = get_subclasses(int)
print_class_hierarchy(list_of_classes)

哪些打印(在Python 3中):

>>> print_class_hierarchy(classes)
builtins.int(builtins.object)
    builtins.bool
    enum.IntEnum(builtins.int, enum.Enum)
        inspect._ParameterKind
        signal.Handlers
        signal.Signals
    enum.IntFlag(builtins.int, enum.Flag)
        re.RegexFlag
    sre_constants._NamedIntConstant
    subprocess.Handle
enum.Enum(builtins.object)
    enum.IntEnum(builtins.int, enum.Enum)
        inspect._ParameterKind
        signal.Handlers
        signal.Signals
enum.Flag(enum.Enum)
    enum.IntFlag(builtins.int, enum.Flag)
        re.RegexFlag

这为我们提供了一个包含所有子类的树,以及相关的多继承类 - 并告诉我们它们所在的模块。