我通过 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 之前或使用 os.linesep 将其转换为字符串,但似乎没有任何效果。有什么方法可以强制消息在 IDLE 上正确显示吗?
如果我提出Exception
(代替KeyError
)那么输出就是我想要的,但我仍然想提出KeyError
如果可能的话。
你的问题与IDLE无关。你看到的行为全部来自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] 应该适用于所有异常。
EDIT
造成差异的原因在这个旧的跟踪器问题,其中引用了评论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__().
*/
该部分出现在KeyError_str
对象定义在Objects/exceptions.c
Python 源代码。
我将提到你的问题作为这种差异的另一种体现。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)