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
模块对话吗?
答案 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