UnicodeDecodeError when registering an exception in Python

I am using Python 2.7.9. x32 on Win7 x64.

When I register an Exception containing Umlauts, I always get UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 39: ordinal not in range(128)

My sample code is:

 except Exception as e: logging.error('Error loading SCMTool for repository ' '%s (ID %d): %s' % (repo.name, repo.id, e), exc_info=1) 

WindowsError: [Error 267] Der Verzeichnisname ist ungültig logged exception WindowsError: [Error 267] Der Verzeichnisname ist ungültig . The problem is based on "ung Ü ltig" umlaut.

After deleting the last %s and e it works without problems.

This happens every time an exception is logged, so changing each registrar is not an alternative.

Does anyone have an idea how to make Exception return a unicode string globally?

+6
source share
1 answer

You are trying to interpolate a unicode object into a str template, causing implicit encoding.

Use unicode pattern; logging can handle Unicode just fine:

 logging.error(u'Error loading SCMTool for repository ' '%s (ID %d): %s' % (repo.name, repo.id, e), exc_info=1) 

Two additional tips:

  • You do not need to do the interpolation yourself; if you pass the three elements for interpolation as separate arguments, logging will interpolate for you, but only if the message is actually issued.

  • If you use logging.exception() , the message is logged at the ERROR level and exc_info set for you; it gets the same result, but is more easily recognized when reading the code later. In any case, an exception is already included in this case; you do not need to include it again in the message.

As such, I would use:

 logging.exception( 'Error loading SCMTool for repository %s (ID %d)', repo.name, repo.id) 
+11
source

Source: https://habr.com/ru/post/982779/


All Articles