我正在将 Python 2 应用程序移植到 Python 3。目前正在运行 Python2.7,但是更新代码以通过 pylint --py3k 测试时,我遇到了一个问题:
def json_resource_file(baseurl, jsondata, resource_info):
"""
Return a file object that reads out a JSON version of the supplied entity values data.
"""
response_file = StringIO()
json.dump(jsondata, response_file, indent=2, separators=(',', ': '), sort_keys=True)
response_file.seek(0)
return response_file
它适用于:
from StringIO import StringIO
但是 StringIO.StringIO 在 Python3 中不存在(根据 pylint),所以使用:
from io import StringIO
我得到一个错误:“TypeError: unicode argument expected, got 'str'”(这是在 Python 2 下运行的——可以这么说,我还在准备基础,并且不打算使用 Python 3,直到我已经在 Python 2 下做了尽可能多的准备和测试。)
通过一些实验,我尝试使用 io 中的 BytesIO,但这给出了不同的错误“TypeError:'unicode' 没有缓冲区接口(interface)”。
很明显,Python2 版本的 json.dump 正在将 str 值写入提供的文件对象。我认为 json.dump 的 Python3 版本也写入 str(即 Unicode)值。
所以我的问题是:是否有一种简单的方法可以将 JSON 转储到适用于 Python 2 和 3 的 StringIO 内存缓冲区?
注意事项
我意识到我可以使用
json.dumps并将结果强制转换为StringIO期望的任何类型,但这一切看起来相当笨拙。我还将使用以下 future 导入作为移植过程的一部分:
from __future__ import (unicode_literals, absolute_import, division, print_function)目前,我想到的解决方案是测试 python 版本并相应地导入不同版本的
StringIO,但这会违反 "Use feature detection instead of version detection"原则。在我的大部分代码中,使用
from io import StringIO似乎适用于我使用StringIO的情况。这是将StringIO与json.dump一起使用的特殊情况,这给我带来了一些问题。
请您参考如下方法:
from six.moves import StringIO
