【问题标题】:Python 2.7: print doesn't speak unicode to the io module?Python 2.7:print 不对 io 模块说 unicode?
【发布时间】:2012-12-21 17:58:23
【问题描述】:
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 模块对话吗?

【问题讨论】:

标签: python unicode io


【解决方案1】:

显然不是。即使你给它一个明确的 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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-08-29
      • 2017-09-13
      • 1970-01-01
      • 2014-02-01
      • 2014-05-02
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 2017-06-19
      相关资源
      最近更新 更多