Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7: print doesn't speak unicode to the io module?

Tags:

python

io

unicode

import sys, codecs, io

codecsout = codecs.getwriter('utf8')(sys.stdout)
ioout = io.open(sys.stdout.fileno(), mode='w', encoding='utf8')
print >> sys.stdout, 1
print >> codecsout, 2
print >> ioout, 3

Fails with:

1
2
Traceback (most recent call last):
  File "print.py", line 7, in <module>
    print >> ioout, 3
TypeError: must be unicode, not str

It fails with print(3, file=ioout) from the __future__ as well.

Does print not know how to talk to the io module?

like image 320
Jay Hacker Avatar asked Aug 15 '26 19:08

Jay Hacker


1 Answers

Evidently it doesn't. Even if you give it an explicit Unicode string, it doesn't work.

>>> print >> ioout, u'3'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be unicode, not str

I'm guessing the problem is in the newline that is automatically appended to the end. The print function from the future doesn't appear to have the same problem:

>>> from __future__ import print_function
>>> print(unicode(3), file=ioout)
3
like image 83
Mark Ransom Avatar answered Aug 18 '26 11:08

Mark Ransom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!