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使用来自__future__的print(3, file=ioout)也会失败。
print不知道如何与io模块对话吗?
发布于 2013-01-08 07:25:52
即使你给它一个显式的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发布于 2013-01-08 10:17:26
print语句对它打印的每一项内容隐式调用__str__。sys.stdout是一个字节流,所以向它发送一个str就可以了。codecs.getwriter是一个旧的Python API,所以我猜它只是像Python2.x传统上那样隐式地将str转换为unicode。然而,与Python3.x一样,新的io模块严格要求将str转换为unicode,这就是它抱怨的原因。
因此,如果要将unicode数据发送到流,请使用.write()方法而不是print。
>>> sys.stdout.write(u'1\n')
1
>>> codecsout.write(u'1\n')
1
>>> sys.stdout.write(u'1\n')
1https://stackoverflow.com/questions/14205548
复制相似问题