我需要存根tempfile
,StringIO
看起来很完美。只是这一切都失败了:
In [1]: from StringIO import StringIO
In [2]: with StringIO("foo") as f: f.read()
--> AttributeError: StringIO instance has no attribute '__exit__'
提供罐头信息而不是读取具有不确定内容的文件的常用方法是什么?
我需要存根tempfile
,StringIO
看起来很完美。只是这一切都失败了:
In [1]: from StringIO import StringIO
In [2]: with StringIO("foo") as f: f.read()
--> AttributeError: StringIO instance has no attribute '__exit__'
提供罐头信息而不是读取具有不确定内容的文件的常用方法是什么?
StringIO 模块早于该with
语句。由于 StringIO已经在 Python 3 中被删除,你可以使用它的替换,io.BytesIO
:
>>> import io
>>> with io.BytesIO(b"foo") as f: f.read()
b'foo'
这个monkeypatch在python2中对我有用。调用monkeypatch
您的初始化例程。
import logging
from StringIO import StringIO
logging.basicConfig(level=logging.DEBUG if __debug__ else logging.INFO)
def debug(*args):
logging.debug('args: %s', args)
return args[0]
def monkeypatch():
'''
allow StringIO to use `with` statement
'''
StringIO.__exit__ = debug
StringIO.__enter__ = debug
if __name__ == '__main__':
monkeypatch()
with StringIO("this is a test") as infile:
print infile.read()
测试运行:
jcomeau@aspire:~/stackoverflow/12028637$ python test.py
DEBUG:root:args: (<StringIO.StringIO instance at 0xf73e76ec>,)
this is a test
DEBUG:root:args: (<StringIO.StringIO instance at 0xf73e76ec>, None, None, None)
jcomeau@aspire:~/stackoverflow/12028637$