Python的StringIO在`with`语句中表现不佳 [英] Python's StringIO doesn't do well with `with` statements
本文介绍了Python的StringIO在`with`语句中表现不佳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要对tempfile
进行存根,并且StringIO
看起来很完美.只是所有这些都失败了:
I need to stub tempfile
and StringIO
seemed perfect. Only that all this fails in an omission:
In [1]: from StringIO import StringIO
In [2]: with StringIO("foo") as f: f.read()
--> AttributeError: StringIO instance has no attribute '__exit__'
提供罐装信息而不是读取不确定内容的文件的常用方法是什么?
What's the usual way to provide canned info instead of reading files with nondeterministic content?
推荐答案
StringIO模块早于with
语句.由于StringIO 无论如何,只要在Python 3中将其删除,就可以使用其替换 io.BytesIO
:
The StringIO module predates the with
statement. Since StringIO has been removed in Python 3 anyways, you can just use its replacement, io.BytesIO
:
>>> import io
>>> with io.BytesIO(b"foo") as f: f.read()
b'foo'
这篇关于Python的StringIO在`with`语句中表现不佳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文