Python 2.7:print不会对io模块说unicode吗?

时间:2013-01-07 22:53:38

标签: python unicode io

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

失败:

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

它也因print(3, file=ioout)中的__future__而失败。

print不知道如何与io模块对话吗?

2 个答案:

答案 0 :(得分:2)

显然它没有。即使你给它一个明确的Unicode字符串,它也不起作用。

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

我猜这个问题出现在自动追加到最后的换行符中。未来的打印功能似乎没有同样的问题:

>>> from __future__ import print_function
>>> print(unicode(3), file=ioout)
3

答案 1 :(得分:0)

print语句在其打印的每个事物上隐式调用__str__sys.stdout是一个字节流,因此发送str就可以了。 codecs.getwriter是一个旧的Python API,所以我猜它只是隐式地将str转换为unicode,就像Python 2.x一样。但是,新的io模块严格按照Python 3.x将str转换为unicode,这就是它抱怨的原因。

因此,如果要将unicode数据发送到流,请使用.write()方法而不是print

>>> sys.stdout.write(u'1\n')
1
>>> codecsout.write(u'1\n')
1
>>> sys.stdout.write(u'1\n')
1