sys.stdout.write()'s bug or doc bug?

Qiangning Hong hongqn at gmail.com
Sun Dec 28 11:37:55 CET 2008


On Dec 27, 12:31 am, Martin <mar... at marcher.name> wrote:
> Python 2.4.4 (#2, Oct 22 2008, 19:52:44)
> [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> u = u"\u554a"
> >>> print u
>> >>> sys.stdout.write(u + "\n")
>
> Traceback (most recent call last):
>  File "<stdin>", line 1, in ?
> UnicodeEncodeError: 'ascii' codec can't encode character u'\u554a' in
> position 0: ordinal not in range(128)
>
> >>> # you are trying to write unicode, you need to encode it to something that suits your needs
> >>> sys.stdout.write(u.encode("UTF-8") + "\n")
>> >>> # now go and write a hundred times "Unicode is not an encoding" :)

Actually, I know relationship between unicode and str objects very
well.  That's why I only quoted the unicode-related part of
file.encoding's documentation in my original post.  Thank you.

> > So, my question is, as sys.stdout IS a file object, why it does not
> > use its encoding attribute to convert the given unicode?  An
> > implementation bug? A documenation bug?
>
> hmm I always thought "sys.stdout" is a "file-like object" not that it IS a file.

In my original post, I have figured out that sys.stdout IS a file, by
using type() function.  And isinstance() function tells the same:

Python 2.5.2 (r252:60911, Dec 18 2008, 12:39:19)
[GCC 4.2.1 (Apple Inc. build 5564)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> type(sys.stdout) is file
True
>>> isinstance(sys.stdout, file)
True

So, sys.stdout SHOULD do what the doc says, otherwise there is a bug
either in implementation of sys.stdout, or in the documentation of
file.



More information about the Python-list mailing list