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

标签 python class exception

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/

相关文章:

java - 将 null 传递给 java 中的重载方法 |重载的变量是Exception类型

python - 按 SQLAlchemy 中的对象过滤

php:对象自动加载 - 值得吗?

css - 在 CSS 中为 ID 和类添加元素类型前缀

php - 当有 __construct() 元素时将类转换为函数

c# - WP8 中的 IsolatedStorageFileStream 不允许操作

java - Java 中的一般异常

Python 正则表达式通过对属于同一类别的元素进行分组

Python Pygal : Setting serie color

python - 如何在 Ubuntu 服务器上手动部署 FastAPI?