>> class BadThings(Exception): ... -6ren">
gpt4 book ai didi

python - 如何从 Python 中用户创建的异常类的开头删除 "__main__."

转载 作者:太空狗 更新时间:2023-10-29 17:48:17 26 4
gpt4 key购买 nike

有没有办法获得一个“更漂亮”的异常而不是一个以 __main__MyExceptionTitle 开头的异常?

例子:

>>> class BadThings(Exception):
... def __init__(self, msg):
... self.msg = msg
... return
...
>>> class BadThings(Exception):
... def __init__(self, msg):
... self.msg = msg
... return
... def __str__(self):
... return self.msg
...
>>> raise BadThings("This is really, really bad")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.BadThings: This is really, really bad

我只想说:

BadThings: This is really, really bad

就像一个类型:

>>> raise Exception("This, too, is really, really bad")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: This, too, is really, really bad

我想要__main__。走了!

谢谢,纳尼

最佳答案

class MyException(Exception):
__module__ = Exception.__module__

这种方式看起来/比 sys.excepthook 效果更好


源代码引用

Python2

参见PyErr_Display

有两种方法可以绕过模块名称部分:

class A(Exception):
__module__ = None

class B(Exception):
__module__ = 'exceptions'

但是如果你需要使用threading.Thread,第一个会引入一个TypeError

python 3

参见PyErr_WriteUnraisable

class C(Exception):
__module__ = 'builtins'

关于python - 如何从 Python 中用户创建的异常类的开头删除 "__main__.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3689727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com