在Python 2/3中打印浮动到io.StringIO

时间:2016-04-18 15:17:03

标签: python python-2.7 stringio

我正在尝试编写一个适用于Python 2.7和Python 3的Python程序。*。我有一个案例,我使用StringIO,根据Python-Future's cheatsheet on StringIO,我所要做的就是使用Python 3风格的io模块。

问题在于我print floats StringIO from __future__ import print_function from io import StringIO with StringIO() as file: print(1.0, file=file)

TypeError: string argument expected, got 'str'

这导致

1.0

当我将u"AAAA"替换为"AAAA"(或unicode_literals并启用BytesIO)时,它可以正常工作。

我试过的替代方案:

  • print。我不能unicode了,因为“"{:f}".format(...)不支持缓冲接口”。
  • 每个float
  • file.write(...)。这是可能的,但很麻烦。
  • print(..., file=file)代替print()。这是有效的,但此时,我还没有看到compile_commands.json的用途。

还有其他选择吗?

1 个答案:

答案 0 :(得分:1)

这就是我对这个问题的处理方式:

import sys

if sys.version_info[0] == 2:  # Not named on 2.6
    from __future__ import print_function
    from StringIO import StringIO
else:
    from io import StringIO

这会打破PEP008的方式(import s应位于文件的顶部),但我个人认为这是合理的。