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

时间:2012-08-19 17:50:15

标签: python unit-testing stringio stubs

我需要存根tempfileStringIO似乎是完美的。只有这一切都失败了:

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

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

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

2 个答案:

答案 0 :(得分:34)

StringIO模块早于with语句。自从StringIO has been removed in Python 3以来,你可以使用它的替换io.BytesIO

>>> import io
>>> with io.BytesIO(b"foo") as f: f.read()
b'foo'

答案 1 :(得分: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$