Welcome, guest | Sign In | My Account | Store | Cart

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()
Python, 15 lines
 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()

3 comments

David Lambert 15 years, 1 month ago  # | flag

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.

arsyed 15 years, 1 month ago  # | flag

The "closing" helper in contextlib is handy for any object with a "close" method:

from contextlib import closing

with closing(StringIO()) as sio:
    function_accepting_file_handle(sio)
    print sio.getvalue()
srid (author) 15 years, 1 month ago  # | flag

@arsyed,

Thanks, I did not know about the closing helper!