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
模块对话?
最佳答案
显然不是。即使你给它一个明确的 Unicode 字符串,它也不起作用。
>>> print >> ioout, u'3'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be unicode, not str
我猜问题出在自动附加到末尾的换行符中。 future 的打印功能似乎没有同样的问题:
>>> from __future__ import print_function
>>> print(unicode(3), file=ioout)
3
关于 python 2.7 : print doesn't speak unicode to the io module?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14205548/