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

Siv*_*lam 12 python exception class

python中的any命令行选项是否打印异常/错误类层次结构?

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

ale*_*cxe 25

检查模块可能有帮助,特别是getclasstree()函数:

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

inspect.getclasstree(inspect.getmro(Exception))
Run Code Online (Sandbox Code Playgroud)

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

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

classtree(BaseException)
Run Code Online (Sandbox Code Playgroud)

打印:

 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
Run Code Online (Sandbox Code Playgroud)