Python's StringIO doesn't do well with `with` statements

五迷三道 提交于 2019-12-04 10:04:33

问题


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?


回答1:


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'



回答2:


this monkeypatch works for me in python2. call monkeypatch in your initialization routine.

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()

test run:

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$


来源:https://stackoverflow.com/questions/12028637/pythons-stringio-doesnt-do-well-with-with-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!