0
votes

I'm rather new at Python and am experiencing some issues printing the contents of an Exception:

# -*- coding: ISO-8859-1 -*-

    except Exception as err:
    print(err)

yields "UnicodeEncodeError: 'ascii' codec can't encode character u'\uf260' in position 52: ordinal not in range(128)"

I've tried reading https://docs.python.org/2.7/howto/unicode.html#the-unicode-type but the issue I'm encountering is that in order to decode and encode or use unicode(..,errors='ignore') I need a string and str(err) fails with the above error message.

This is in a Windows environ. Thankful for any replies, even if it is "learn to search!" because in that case there was indeed a similar question that I missed while searching that's hopefully been answered : )

Edit. I've tried

print("Error {0}".format(str(err.args[0])).encode('utf-8', errors='ignore'))

which yields exactly the same error message.

1

1 Answers

0
votes

UnicodeEncodeError: 'ascii' codec can't encode character u'\uf260' in position 52: ordinal not in range(128)

Look in the error, character \uf260 its not ascii, but something is trying to treat a non-ascii character as ascii. What?

Try this instead : print err.__repr__() .

Explanation:

err is an Exception object which has __str__() function implemented, so on printing an object object.__str__() method is called which essentially brings this error. You can verify by calling print err.__str__() to get similar error.

Also to check that Exception class module has __str__(), you can do dir(Exception).

Update: Check this link to understand how print picks up encoding.

References:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

Python __str__ versus __unicode__

How to print a class or objects of class using print()?

Python: Converting from ISO-8859-1/latin1 to UTF-8

Why does Python print unicode characters when the default encoding is ASCII?