Supporting read() with fileinput?

D

Daniel Yoo

Hi everyone,

I'm was wondering: would it be a good idea to have the FileInput class
support a read() method? I found myself running into a small problem
while using xml.sax.parse in combination with fileinput. Here's a
snippet that demonstrates the problem:

###
import xml.sax
import fileinput

xml.sax.parse(fileinput.input(), xml.sax.ContentHandler())
###

This doesn't work, because fileinput.input() isn't a file-like object:
it doesn't have read(), so it can't be converted into a nice InputSource.


But I thought it might be nice to have one, so I cooked up a quick
class to make it work:

###
class ByteStream:
def __init__(self, f):
self._buffer = []
self._f = f

def read(self, bytes):
if not self._buffer: self._prime()
next_block = self._buffer[:bytes]
del self._buffer[:bytes]
return ''.join(next_block)

def _prime(self):
self._buffer.extend(list(self._f.readline()))
###

And now I can get:

###
xml.sax.parse(ByteStream(fileinput.input()), xml.sax.ContentHandler())
###

to work. But I'd rather make this solution a bit more permanent.
*grin* Would it be a good idea to add a read() method to FileInput to
make it more file-like?


Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top