Unicode thing that causes a traceback in 2.6 and 2.7 but not in 2.5, and only when writing to a pipe, not to the terminal

Piet van Oostrum piet at vanoostrum.org
Thu Dec 2 12:03:58 EST 2010


Dan Stromberg <drsalists at gmail.com> writes:

> What is this about?  It's another n~ thing, but this time in 2.x.
> All I'm doing is printing a str containing a character > 127.
>
> It works fine in 2.5, to a terminal or to a pipe.  In 2.6 and 2.7, it
> fails when writing to a pipe but works fine writing to my terminal -
> an mrxvt.\
>
> I really kind of want octets to just be octets, since I'm on a Linux
> system - it probably should be up to the user and their related
> software to decide how those octets are interpreted.  I'm assuming
> that the bytes() workarounds I'm using in 3.x aren't going to work in
> 2.x - it looks like bytes() is just an alias for str() in 2.6 and 2.7.

Strings are indeed byte strings (or octet strings if you prefer) in Python 2.x.

> Traceback (most recent call last):
>   File "./test-readline0", line 22, in <module>
>     print(line)
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in
> position 20: ordinal not in range(128)

This message shows that line is not a byte string but a unicode string.
If you want to output a unicode string it has to be converted to bytes
first, and Python must know which encoding to use. For output to the
terminal it can usually get that information from the system, but not
for a pipe. You will have to supply it.

By the way, if you just want to work with octets, why is the variable
line in unicode? If you keep everything in byte strings your problem may
disappear. In Python 3 you have to do this explicitely as the default is unicode.
-- 
Piet van Oostrum <piet at vanoostrum.org>
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]
Nu Fair Trade woonartikelen op http://www.zylja.com



More information about the Python-list mailing list