python-3.x - KeyError 中错误消息的新行 - Python 3.3

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

我通过 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] 应该适用于所有异常。

编辑

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 源代码的 Objects/exceptions.c 中的 KeyError_str 对象定义中。

我将提及您的问题,作为这种差异的另一种体现。

关于python-3.x - KeyError 中错误消息的新行 - Python 3.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46892261/

相关文章:

python - 使用分组依据并创建 CSV

python - 为什么我的 python 代码在调试器中按预期运行而不是其他方式?

json - Swift 3-JSON解析

python - 如何在没有闲置的情况下安装python?

python - 从命令行启动 Python IDLE 以编辑脚本

python - 使用索引和值过滤 Pandas 系列

python - 在 Python 3 中读取 MP3

bash - 当其中一个后台进程出错时如何退出 bash 脚本?

python-3.x - 字典中缺失值的错误处理

objective-c - 需要 iOS 引用来了解 sleep 、待机和/或空闲模式下发生的情况