【问题标题】:How to use 'io.StringIO' with 'print >>'?如何将 'io.StringIO' 与 'print >>' 一起使用?
【发布时间】:2018-11-13 00:16:18
【问题描述】:

我收到以下错误:

 Second line.
Traceback (most recent call last):
  File "./main.py", line 8, in <module>
    print >>output, u'Second line.'
TypeError: unicode argument expected, got 'str'

当我运行以下代码时。我不知道出了什么问题。谁能告诉我如何解决它?

#!/usr/bin/env python
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:

import io
output = io.StringIO()
output.write(u'First line.\n')
print u'Second line.'
print >>output, u'Second line.'
contents = output.getvalue()
print contents
output.close()

【问题讨论】:

    标签: python python-2.7 stringio


    【解决方案1】:

    对于 Python 2,请考虑使用 StringIO 模块而不是 io。

    代码:

    from StringIO import StringIO
    

    测试代码:

    from StringIO import StringIO
    output = StringIO()
    output.write(u'First line.\n')
    print u'Second line.'
    print >>output, u'Second line.'
    contents = output.getvalue()
    print contents
    output.close()
    

    结果:

    Second line.
    First line.
    Second line.
    

    【讨论】:

    • 您的意思是print contents.encode('utf-8'),因为内容的类型是unicode?另外,io.StringIO 在 python2 中可用,什么时候应该使用它而不是 StringIO.StringIO
    • io 是可用的,但它是 Python 3 的反向端口。显然打印重定向会混淆它。您正在使用仅 Python2 的功能,因此可以使用 StringIO 模块。
    • 如果你想使用反向移植的io.StringIO,你也应该使用反向移植的printfrom __future__ import print_function
    猜你喜欢
    • 2012-10-18
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2014-09-25
    • 2016-01-30
    • 2015-12-13
    相关资源
    最近更新 更多