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はPython3で削除されているので、代わりに使用できますio.BytesIO

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

このモンキーパッチは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 に答える