python 中的 any 命令行选项是否用于打印异常/错误类层次结构?
输出应该类似于http://docs.python.org/2/library/exceptions.html#exception-hierarchy
最佳答案
inspect模块可能有帮助,特别是 getclasstree()功能:
Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list.
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
关于python - 打印 Python 异常/错误层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18296653/