像 Python 一样格式化异常

问题描述 投票:0回答:2

如果我在 Python 中引发异常,我会得到以下结果:

raise Exception("Hello world")
Traceback (most recent call last):

  File "<ipython-input-24-dd3f3f45afbe>", line 1, in <module>
    raise Exception("Hello world")

Exception: Hello world

注意最后一行“

Exception: Hello world
”。遇到异常 (
foo = Exception("Hello world")
),我怎样才能生成这样的文本?以下均无效:

str(foo)
Out[27]: 'Hello world'

repr(foo)
Out[28]: "Exception('Hello world',)"

"{}".format(foo)
Out[29]: 'Hello world'

"{}: {}".format(type(foo), foo)
Out[30]: "<type 'exceptions.Exception'>: Hello world"
python exception string-formatting
2个回答
19
投票

如果您的异常对象是

exc
,那么:

  • 冒号之前的部分是
    type(exc).__name__
  • 冒号后面的部分是
    str(exc)

所以你可以这样做:

print('{}: {}'.format(type(exc).__name__, exc))

15
投票

使 tdelaney 的答案正式并展示差异......

弦乐

#test.py
import traceback

try :
    raise TypeError("Wrong Type baby!")

except Exception as e:
    print( "EXCEPTION FORMAT PRINT:\n{}".format( e ) )
    print( "EXCEPTION TRACE  PRINT:\n{}".format( "".join(traceback.format_exception(type(e), e, e.__traceback__))

控制台输出结果

EXCEPTION FORMAT PRINT:
Wrong Type baby!
EXCEPTION TRACE  PRINT:
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    raise TypeError("Wrong Type baby!")
TypeError: Wrong Type baby!

记录

如果您处于日志记录的上下文中,还有 exception 方法和

exc_info
kwarg 可以为您进行格式化。我们应该注意,由于根记录器将警告作为其默认日志级别,因此调试和信息级别的日志消息将被忽略。

# logTest.py
import logging

try :
    raise ValueError("my bad value")
except Exception as e :
    logging.exception( e )
    logging.debug("\n{}\nDEBUG LEVEL EXAMPLE".format('-'*30), exc_info=e)
    logging.info("\n{}\nINFO LEVEL EXAMPLE".format('-'*30), exc_info=e)
    logging.warning("\n{}\nWARNING LEVEL EXAMPLE".format('-'*30), exc_info=e)
    logging.error("\n{}\nERROR LEVEL EXAMPLE".format('-'*30), exc_info=e)

控制台输出结果...

ERROR:root:my bad value
Traceback (most recent call last):
  File "/Users/me/logTest.py", line 5, in <module>
    raise ValueError("my bad value")
ValueError: my bad value
WARNING:root:
------------------------------
WARNING LEVEL EXAMPLE
Traceback (most recent call last):
  File "/Users/me/logTest.py", line 5, in <module>
    raise ValueError("my bad value")
ValueError: my bad value
ERROR:root:
------------------------------
ERROR LEVEL EXAMPLE
Traceback (most recent call last):
  File "/Users/me/logTest.py", line 5, in <module>
    raise ValueError("my bad value")
ValueError: my bad value
© www.soinside.com 2019 - 2024. All rights reserved.