vagueish questions on use of file/string objects

John Machin sjmachin at --nospam--lexicon.net
Tue Jan 29 08:55:32 EST 2002


"Keith Keller" <kkeller at speakeasy.net> wrote in message
news:5dc53a.kmo.ln at wombat.san-francisco.ca.us...

^^^^^^^^^^^^^^^^^^^^^^^^^^
What's a wombat doing in SFO?

> Okay, bear with me here.
>
> I've just started coding a little Python, and I ran into a bit of
> a snag.  I would like to generate a news posting from sys.stdin, but
> only after doing some manipulations on it, mostly with the headers.
> Being stdin, though, it's not really possible to manipulate well, so
> I've been putting the post text into a string.
>
> However, the nntplib module demands a file object for its post method.
> So, I have five options:

I see only three.

>
> ==Open a temp file, put the post there, then use it with post.

Yuk.

>
> ==Subclass NNTP, and create a new method that accepts a string instead
> of a file (or override the post method which can detect whether it's
> being passed a file object or string object and act accordingly).

Yuk * sys.maxint

> ==Create a fake file object that's not on disk, and pass it to the
> nntplib post method.  I looked all over the place for docs on how to do
> this, but couldn't find anything helpful.  Either I'm clueless, the
> docs are buried, or they don't exist.

... or you're suffering from paradigm shock :-)

Brief inspection of the post method in nntplib shows that it expects its
file argument f to support only the readline method. Therefore we have to
supply an object with some data and a readline method to dole it out on
request ... post() won't care, so long as it quacks like a duck.

>>> class Fakefile:
...    def __init__(self, theData):
...       self.guff = theData
...    def readline(self):
...       k = self.guff.find('\n')
...       if k < 0:
...          result = self.guff
...       else:
...          result = self.guff[:k+1]
...       self.guff = self.guff[k+1:]
...       return result
...
>>> someData = 'blah blah\nrabbit rabbit\n'
>>> theFake = Fakefile(someData) # construct an instance of the Fakefile
class
>>> theFake.readline() # check it has the desired behaviour
'blah blah\n'
>>> theFake.readline()
'rabbit rabbit\n'
>>> theFake.readline()
''
>>>

So all you have to do, create an instance of Fakefile, initialising it with
your newline-embedded string of data, and pass it off to nntplib's post as
the real thing.

If nntplib were modernised, it would use
   for line in f:
instead of f.readline(), and it would publish that f could be any old
iterable object which produced  newline-terminated strings, and you could
rewrite Fakefile as a generator ...

HTH,
John





More information about the Python-list mailing list