您只测试了InputType
,这是一个cStringIO.StringIO()
支持阅读的实例。您似乎拥有另一种类型,OutputType
即为支持写入的实例创建的实例:
>>> import cStringIO
>>> finput = cStringIO.StringIO('Hello world!') # the input type, it has data ready to read
>>> finput
<cStringIO.StringI object at 0x1034397a0>
>>> isinstance(finput, cStringIO.InputType)
True
>>> foutput = cStringIO.StringIO() # the output type, it is ready to receive data
>>> foutput
<cStringIO.StringO object at 0x102fb99d0>
>>> isinstance(foutput, cStringIO.OutputType)
True
您需要测试这两种类型,只需使用这两种类型的元组作为第二个参数isinstance()
:
from cStringIO import StringIO, InputType, OutputType
if not isinstance(content, (InputType, OutputType)):
content = StringIO(content)
或者,这是更好的选择,测试read
和seek
属性,因此您还可以支持常规文件:
if not (hasattr(content, 'read') and hasattr(content, 'seek')):
# if not a file object, assume it is a string and wrap it in an in-memory file.
content = StringIO(content)
或者您可以只测试字符串和 [buffers]( https://docs.python.org/2/library/functions.html#buffer (,因为它们是唯一StringIO()
可以支持的两种类型:
if isinstance(content, (str, buffer)):
# wrap strings into an in-memory file
content = StringIO(content)
这具有额外的好处,Python 库中的任何其他文件对象,包括压缩文件,tempfile.SpooledTemporaryFile()
并且io.BytesIO()
也将被接受和工作。