简体   繁体   English

Python 3例外不打印新行

[英]Python 3 exception not printing new line

I do not really know how to say it, but when I raise exception in python 3.2, '\\n' aren't parsed ... 我真的不知道怎么说,但是当我在python 3.2中引发异常时,'\\ n'没有被解析 ...

Here is an example: 这是一个例子:

class ParserError(Exception):
    def __init__(self, message):
            super().__init__(self, message)

try:
    raise ParserError("This should have\na line break")
except ParserError as err:
    print(err)

It works like this: 它的工作原理如下:

$ ./test.py
(ParserError(...), 'This should have\na line break')

How do I make sure new lines are printed as new lines? 如何确保新行打印为新行?

class ParserError(Exception):
    pass

or 要么

print(err.args[1])

啊,err.message在2.6中被弃用 - 所以不再存在,所以...

print(err.args[1])

What's happening here is that the repr of your message string is being printed as part of passing the whole Exception object to print() , so the newline is being converted back into \\n . 这里发生的是你的消息字符串的repr被打印为将整个Exception对象传递给print() ,因此换行符被转换回\\n If you individually print the actual string, the actual newline will print. 如果单独print实际字符串,则会打印实际换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM