Pergunta

If I do:

logging.debug('subject: '+subject)
logging.debug('body: '+body)

then it works well. If I replace it with:

logging.debug('subject: %s, body: %s' % (subject, body))

then I get

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)

How to avoid this error?

Upd. added second variable body. subject and body are string variables.

Foi útil?

Solução

This is how i would use it:

logging.debug(u'subject: %s', subject)

In your case subject seems to be unicode. So the format should also be unicode.

When you do 'subject: '+subject, if one of the operands is unicode, the other is converted to unicode automatically.

Pay attention that i did debug(u'subject: %s', subject) instead of debug(u'subject: %s' % subject) - so the string is formatted only when logger is actually emitting a record.

Outras dicas

That is how it should be used (python 2.7):

logging.debug('subject: %s' % subject)

e.g. using format specifications with print:

>>> sr = "aaaaaa"
>>> print "d%s" % s
daaaaaa
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top