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

时间:2017-10-23 14:47:44

标签: python-3.x error-handling python-idle

我通过IDLE使用Python 3.3。在运行看起来像这样的代码时:

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

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

Exception

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

如果我举起KeyError(而不是KeyError),那么输出就是我想要的,但如果可能,我还想提出import matplotlib.pyplot as plt import pandas plt.scatter(x=df['Bachelors degree'], y=df['Median Income']) plt.show()

1 个答案:

答案 0 :(得分:5)

你的问题与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]应该适用于所有异常。

修改

差异的原因在this old tracker issue中给出,引用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源代码的KeyError_str中的Objects/exceptions.c对象定义中。

我会提到你的问题,作为这种差异的另一种表现形式。