NOTE: Consider this recipe obsolete. Instead use contextlib.closing
(see comment below).
This contextmanager adds 'with' statement support for StringIO. Peruse the following simple example:
with StringIO() as sio:
function_accepting_file_handle(sio)
print sio.getvalue()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | @contextmanager
def StringIO():
"""Add support for 'with' statement to StringIO - http://bugs.python.org/issue1286
"""
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
sio = StringIO()
try:
yield sio
finally:
sio.close()
|
Tags: stringio, with_statement
I prefer sio.seek(0) ... sio.read() to sio.getvalue()
thus for me a recipe like
with StringIO_Loader(stream_filler) as sio: use(sio)
y such that StringIO_Loader calls stream_filler with a string IO object, seeks to start, and returns sio, and closes at end of context would be really great.
The "closing" helper in contextlib is handy for any object with a "close" method:
@arsyed,
Thanks, I did not know about the
closing
helper!