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

标签 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

__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/

相关文章:

python - 将数据类数组序列化为 JSON

python - 使用Python从Docker容器内获取MYSQL_TCP_ADDR?

python - 在Python中将Unicode写入文件

python - shlex.split 仍然不支持 unicode?

java - 你如何防止 scanner.next() 包含换行符?

python - 将输入从一个 Dash DataTable 输入到第二个 Dash DataTable

python - 使用 CEFPython 为 Chromium 嵌入式框架定义自定义方案处理程序

java - 如何将 arraylist 写入二进制文件

c# - StartsWith Windows Server 2012 中的更改

c# - IO 101 : Which are the main differences between TextWriter, FileStream 和 StreamWriter?