如何删除"__main__".从用户创建的Python异常类开始

nar*_*nie 13 python exception class

有没有办法获得一个"更漂亮"的例外而不是一个前言__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
Run Code Online (Sandbox Code Playgroud)

我想它只是说:

BadThings:这真的非常糟糕

就好像有一种类型:

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

我想要的__main__.走了!

谢谢,纳妮

you*_*ufu 6

class MyException( Exception ):
    __module__ = Exception.__module__
Run Code Online (Sandbox Code Playgroud)

这种方式看起来/比 sys.excepthook


源代码参考

Python2

看到 PyErr_Display

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

class A( Exception ):
    __module__ = None

class B( Exception ):
    __module__ = 'exceptions'
Run Code Online (Sandbox Code Playgroud)

但是,如果您需要玩threading.Thread,第一个会介绍一个TypeError

Python 3

看到 PyErr_WriteUnraisable

只有第二种方法有效。使用builtins代替exceptions


Anu*_*yal 5

我不确定你为什么要删除,__main__因为这是模块名称,当你的异常位于适当命名的模块中时,它会看起来很漂亮而不是丑陋,例如myexceptions.BadException

或者,您可以捕获异常并根据需要进行打印。

但是如果您希望按照您的意愿打印未捕获的异常,请尝试设置sys.excepthook例如

class BadThings(Exception): pass 

import traceback
def myexcepthook(type, value, tb):
    l = ''.join(traceback.format_exception(type, value, tb))
    print l

import sys
sys.excepthook = myexcepthook

raise BadThings("bad bad")
Run Code Online (Sandbox Code Playgroud)

输出:

Traceback (most recent call last):
  File "untitled-1.py", line 12, in <module>
    raise BadThings("bad bad")
BadThings: bad bad
Run Code Online (Sandbox Code Playgroud)

所以sys.excepthook你可以修改异常,格式化它等