Python的StringIO的不`with`报表做得很好(Python's StringI

2019-07-31 01:48发布

我需要存根tempfileStringIO似乎是完美的。 只有这一切都未能在遗漏:

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

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

什么是罐头提供的信息,而不是读与不确定性的内容文件通常的方式?

Answer 1:

StringIO模块是早于with声明。 由于StringIO的已经在Python 3被删除反正,你可以用它替代, io.BytesIO

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


Answer 2:

这猴补丁在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$


文章来源: Python's StringIO doesn't do well with `with` statements