file.getvalue() with _ or other characters

Peter Hansen peter at engcorp.com
Thu Mar 3 08:25:58 EST 2005


martijn at gamecreators.nl wrote:
> file = StringIO.StringIO()
> f = formatter.AbstractFormatter(formatter.DumbWriter(file))
> p = mvbHTMLParser(f)
> p.feed(html)
> p.close()
> 
> print file.getvalue()
> 
> But then the _ characters are away.
> is it possible to keep that character in file.getvalue()

I consider this a defect in StringIO, but it's pretty easy to
fix it, at least for the narrow usage you describe:

class PreservingStringIO(StringIO.StringIO):
     def close(self):
         pass

file = PreservingStringIO()
...etc

The problem is (if I'm right about this) that the close()
method on the object returned by mvbHTMLParser() will actually
call close() on the file object in the formatter (whether
directly or not, I don't know).  One might consider _this_
a bug as well, but if the above approach works, in the end
it's no big deal.

So basically redefine close() to do nothing (or have it save
a copy of the buffer's getvalue() results first) and you
should be good to go.

-Peter



More information about the Python-list mailing list