19

我需要存根tempfileStringIO看起来很完美。只是这一切都失败了:

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

--> AttributeError: StringIO instance has no attribute '__exit__'

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

4

2 回答 2

35

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

>>> import io
>>> with io.BytesIO(b"foo") as f: f.read()
b'foo'
于 2012-08-19T17:58:17.703 回答
3

这个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$
于 2016-09-05T20:38:45.537 回答