简体   繁体   English

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

[英]printing floats to io.StringIO in Python 2/3

I'm trying to write a Python program that works in both Python 2.7 and Python 3.*.我正在尝试编写一个适用于 Python 2.7 和 Python 3.* 的 Python 程序。 I have a case where I use StringIO , and according to Python-Future's cheatsheet on StringIO , all I have to to is to use the Python 3-style io module.我有一个使用StringIO ,根据Python-Future 关于StringIO ,我所StringIO就是使用 Python 3-style io模块。

The problem is that I'm print ing floats to this StringIO :问题是我正在print floats到这个StringIO

from __future__ import print_function
from io import StringIO

with StringIO() as file:
    print(1.0, file=file)

This results in这导致

TypeError: string argument expected, got 'str'

When I replace 1.0 by u"AAAA" (or "AAAA" with unicode_literals enabled), it works fine.当我用u"AAAA" (或启用unicode_literals "AAAA" )替换1.0 ,它工作正常。

Alternatives I've tried:我尝试过的替代方案:

  • BytesIO . BytesIO I can't print anymore, because " unicode doesn't support the buffer interface".我不能再print了,因为“ unicode不支持缓冲区接口”。
  • "{:f}".format(...) every float . "{:f}".format(...)每个float This is possible, but cumbersome.这是可能的,但很麻烦。
  • file.write(...) instead of print(..., file=file) . file.write(...)而不是print(..., file=file) This works, but at this point, I don't see what the use of print() is anymore.这有效,但在这一点上,我看不到print()的用途了。

Are there any other options?还有其他选择吗?

This is what I do with this issue:这就是我对这个问题所做的:

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

This breaks PEP008 by the way ( import s should be at the top of the file), but personally I think it is justified.顺便说一下,这打破了 PEP008( import应该在文件的顶部),但我个人认为这是有道理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM