Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

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])
like image 362
user1530147 Avatar asked Jul 17 '12 14:07

user1530147


2 Answers

Ahh, err.message was deprecated in 2.6 - so no longer present, so...

print(err.args[1])
like image 145
Jon Clements Avatar answered Sep 18 '22 16:09

Jon Clements


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. If you individually print the actual string, the actual newline will print.

like image 29
Wooble Avatar answered Sep 20 '22 16:09

Wooble