2

Given the simple script:

#!/usr/bin/env python3

b = 'строка'.encode()
print(b.decode('utf-8'))

If I run it directly as python3 script.py or /full/path/to/script.py or indirectly through crontab (e.g. 0 0 * * * /full/path/to/script.py) then it's executed normally (without errors). But when it's executed through fcrontab for the same $USER (with same job 0 0 * * * /full/path/to/script.py) then Python 3.5.2 raise exception:

Traceback (most recent call last):
  File "/full/path/to/script.py", line 4, in <module>
    print(b.decode('utf-8')) 
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

How can it be possible? Why does Python try decode bytes as 'ascii' instead of 'utf-8'?

kupgov
  • 383
  • 6
  • 16
  • 1
    See here https://wiki.python.org/moin/PrintFails – Daniel Voina Sep 16 '16 at 06:14
  • Oh, it's really problem with only `print` function because of locale that's set for fcron (in my case fcron has locales 'POSIX' instead of *.UTF-8)... Thank you! – kupgov Sep 16 '16 at 06:32

1 Answers1

2

Thanks to Daniel Voina solution was found.

The problem is because of locale environment of fcron: it replaces default locale with POSIX, so Python cannot write unicode to stdout/stderr.This thread describes solution for this problem: it's only necessary add line LC_ALL=en_US.UTF-8 (or other locale settings) at the top of fcrontab -e and now script executes without I/O errors.

Example of fcrontab -l:

LC_ALL=en_US.UTF-8
LC_TIME=ru_RU.UTF-8
0 0 * * * /full/path/to/script.py
kupgov
  • 383
  • 6
  • 16