UnicodeEncodeError only when running as a cron job

Question:

My program works right in the commandline, but when I run it as a cron job it crashes on the error:

UnicodeEncodeError: 'ascii' codec can't encode character
u'xa7' in position 13: ordinal not in range(128)

It crashes on the statement

print title

Why this is happening only when the app runs as a cron job? How could this be fixed?

I tried (with no help):

print unicode(title)

Python is 2.7

Asked By: xralf

||

Answers:

Aside: This is a common problem; as such this is probably a duplicate question.

The default encoding on 2.7 is ascii.
You need to provide an encoding for your program’s output.
A common encoding to use is ‘utf8’.

So you’d do instead:

print title.encode('utf8')

Here’s one way to check the default encoding:

import sys

sys.getdefaultencoding()
# -> 'ascii'
Answered By: mechanical_meat

Nah, you can have it simpler. Just define PYTHONIOENCODING before executing this script. Like this:

PATH=<your path>
MAILTO=someone@somewhere
PYTHONIOENCODING=utf8

* * * * * /run/your/script
Answered By: kworr
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.