Python的StringIO与`with`语句不相符

unp*_*680 19 python unit-testing stringio stubs

我需要存根tempfile并且StringIO看起来很完美.只有这一切都失败了:

In [1]: from StringIO import StringIO
In [2]: with StringIO("foo") as f: f.read()

--> AttributeError: StringIO instance has no attribute '__exit__'
Run Code Online (Sandbox Code Playgroud)

提供固定信息而不是读取具有不确定内容的文件的常用方法是什么?

phi*_*hag 34

StringIO模块早于with语句.由于StringIO 已经在Python 3中删除了,你可以使用它的替换,io.BytesIO:

>>> import io
>>> with io.BytesIO(b"foo") as f: f.read()
b'foo'
Run Code Online (Sandbox Code Playgroud)

  • 请注意,`io`模块在Python 2.6中是纯python,而Python 2.7使用Python 3.1的快速C实现.所以对于Python 2.6,使用`io.BytesIO`会导致性能下降. (3认同)
  • 未删除,来自 Python 3.0 的新增功能:StringIO 和 cStringIO 模块消失了。相反,导入 io 模块并分别将 io.StringIO 或 io.BytesIO 用于文本和数据。 (2认同)