I have the following script (test.py), printin a non-ASCII character:
# -*- coding: utf-8 -*-
print u"café"
It works as expected when running at shell:
$ python test.py
café
However, if I try the usual bash redirect with > it fails in the following way:
$ python test.py > result.txt
Traceback (most recent call last):
File "test.py", line 2, in <module>
print u"café"
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128)
How this can be solved?
Python version, in the case it helps:
$ python --version
Python 2.6.6
EDIT1: note this question is not a duplicated of this other. In the referred question they are using file abstraction in Python, e.g. open(), etc. while in my question these abstractions are not used and I'm using bash redirection.
EDIT2: check bash unicode support, as suggested in comments:
$ bash --version | head -n 1
GNU bash, versión 4.1.2(1)-release (x86_64-redhat-linux-gnu)
$ stty -a
speed 38400 baud; rows 35; columns 150; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = M-^?; eol2 = M-^?; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;
werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts -cdtrdsr
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc ixany imaxbel -iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke
$ echo -e '\xe2\x82\xac'
€