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$
io
module is pure-python in Python 2.6, while Python 2.7 uses Python 3.1's fast C implementation. So for Python 2.6 only, usingio.BytesIO
will result in a performance penalty. – Grahamgrahame