KeyError语言 - Python 3.3 中错误消息上的新行



我通过IDLE使用Python 3.3。在运行如下所示的代码时:

raise KeyError('This is a n Line break')

它输出:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    raise KeyError('This is a n Line break')
KeyError: 'This is a n Line break'

我希望它输出带有换行符的消息,如下所示:

This is a
 Line Break

我之前或使用 os.linesep 尝试将其转换为字符串,但似乎没有任何效果。有什么方法可以强制消息在空闲时正确显示?


如果我提出一个Exception(而不是KeyError),那么输出就是我想要的,但如果可能的话,我仍然想提高一个KeyError

您的问题与空闲无关。 你看到的行为都来自Python。 从命令行以交互方式运行当前存储库 CPython,我们会看到您报告的行为。

Python 3.7.0a2+ (heads/pr_3947:01eae2f721, Oct 22 2017, 14:06:43)
[MSC v.1900 32 bit (Intel)] on win32
>>> raise KeyError('This is a n Line break')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'This is a n Line break'
>>> s = 'This is a n Line break'
>>> s
'This is a n Line break'
>>> print(s)
This is a
 Line break
>>> raise Exception('This is a n Line break')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: This is a
 Line break
>>> raise IndexError(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: This is a
 Line break
>>> try:
...   raise  KeyError('This is a n Line break')
... except KeyError as e:
...   print(e)
'This is a n Line break'
>>> try:
...   raise  KeyError('This is a n Line break')
... except KeyError as e:
...   print(e.args[0])
This is a
 Line break

我不知道为什么KeyError的行为与IndexError不同,但是打印e.args[0]应该适用于所有异常。

编辑

差异的原因在这个旧的跟踪器问题中给出,它引用了KeyError源代码中的注释:

/* If args is a tuple of exactly one item, apply repr to args[0].
       This is done so that e.g. the exception raised by {}[''] prints
         KeyError: ''
       rather than the confusing
         KeyError
       alone.  The downside is that if KeyError is raised with an
explanatory
       string, that string will be displayed in quotes.  Too bad.
       If args is anything else, use the default BaseException__str__().
    */

此部分显示在 Python 源代码Objects/exceptions.cKeyError_str对象定义中。

我将提到您的问题作为这种差异的另一种表现。

一种方法可以获取您想要的行为: 只需子类str并覆盖__repr__

    class KeyErrorMessage(str):
        def __repr__(self): return str(self)
    msg = KeyErrorMessage('Newlineninnkeynerror')
    raise KeyError(msg)

指纹:

回溯(最近一次调用):
...
文件 ",第 5 行,在
引发密钥错误(msg)
键错误:换行
符在
.key
错误

最新更新