在异常消息中打印换行符

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

为什么不能在屏幕上打印两行?

raise KeyError('a\na')

(编辑)

为什么它可以与

ValueError
一起使用?

我需要能够在异常情况下打印出项目符号列表。

python exception printing
2个回答
0
投票

最简单的方法是将其转换为字符串并用换行符分割:

try:
    raise KeyError('a\na')
except KeyError as e:
    strw = str(e)[1:-1].split('\\n')
    for s in strw:
        print(s)

看起来您必须使用

\\n
作为分隔符,并且引号应该被丢弃。


0
投票

我也遇到了这个问题并且很好奇。事实证明,原因记录在源代码中:

KeyError
覆盖了
__str__
,这样如果它收到空字符串
''
,用户将不会收到令人困惑的错误消息。

引用 来自 CPython 3.12 源代码

/*
 *    KeyError extends LookupError
 */
static PyObject *
KeyError_str(PyBaseExceptionObject *self)
{
    /* 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__().
    */
    if (PyTuple_GET_SIZE(self->args) == 1) {
        return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
    }
    return BaseException_str(self);
}

© www.soinside.com 2019 - 2024. All rights reserved.