我正在将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参数,得到'str'”(这是在Python 2下运行 - 我还在准备基础,可以这么说,我不打算使用Python 3,直到我完成我可以在Python 2下进行大量准备和测试。)
通过一些实验,我尝试使用来自BytesIO
的io
,但这给出了一个不同的错误“TypeError:'unicode'没有缓冲接口”。
显然,json.dump的Python2版本正在将str
值写入提供的文件对象。我认为json.dump的Python3版本也写了str
(即Unicode)值。
所以我的问题是:是否有一种简单的方法可以将JSON转储到与Python 2和3一起使用的StringIO内存缓冲区?
json.dumps
并将结果强制到StringIO
所期望的任何类型,但这一切看起来都相当严厉。from __future__ import (unicode_literals, absolute_import, division, print_function)
StringIO
,但这会违反"Use feature detection instead of version detection"原则。from io import StringIO
似乎适用于我使用StringIO
的情况。这是使用StringIO
和json.dump
的特定情况,这给我带来了一些问题。from six.moves import StringIO
如果您的问题是import语句,只需将其包装在try语句中:
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
你的其余代码应该按原样运行,至少你问题中提供的代码对我来说很合适。