[ale] Python regex (Now: readline())

Christopher Fowler cfowler at outpostsentinel.com
Mon Sep 11 11:33:21 EDT 2006


On Mon, 2006-09-11 at 11:21 -0400, Alex LeDonne wrote:
> On 9/10/06, Christopher Fowler <cfowler at outpostsentinel.com> wrote:
> > Is there a readline method in a class that can turn a socket into
> > buffered I/O?  I'm writing a class to interface with a server on an
> > embedded device and I need to interact by line.
> >
> > I simply added it to my class since my class is the client to the server
> > --------[ Cut Here ] ---------------------------------------------------
> >   def readline(self):
> >     buffer = None
> >     if self.socket is None: return None
> >
> >     data = self.socket.recv(1)
> >
> >     while data is not None:
> >       if buffer is None:
> >         buffer = str(data)
> >       else:
> >         buffer = buffer + str(data)
> >
> >       if data.startswith("\n"):
> >         return buffer
> >
> >       # No NL yet.  Read again
> >       data = self.socket.recv(1)
> >
> >     # If we get here then we've encountered
> >     # an EOF condition.  Return the buffer. The
> >     # next call to readline will cause None
> >     # to be sent to caller
> >     return buffer
> >
> > --------[ Cut Here ] ---------------------------------------------------
> > Not sure if that is the best way?  But it works.
> >
> 
> This seems... inefficient. I think you should safely be able to read a
> much larger chunk at a time, say data = self.socket.recv(1024). If
> there's a newline, then len(data) < 1024. The only thing you have to
> check is if len(data) == 1024, whether data.endswith("\n").
> 
> By the way, you'll want to test data against '' (empty string) -
> that's what recv will return if the socket disconnects.
> 

I did not know that was the way recv worked

Here is the new method:
  def readline(self, timeout=0):
    buffer = None
    if self.__socket is None: return None

    data = self.read(1024,timeout)

    while data is not None:
      if buffer is None:
        buffer = str(data)
      else:
        buffer = buffer + str(data)

      if len(data) is 1024 and data.endswith("\n"):
        return buffer
      else:
        return buffer

      # No NL yet.  Read again
      data = self.read(1024,timeout)

    # If we get here then we've encountered
    # an EOF condition.  Return the buffer. The
    # next call to readline will cause None
    # to be sent to caller
    return buffer


I thought recv returns None on socket disconnect?

> -A
> _______________________________________________
> Ale mailing list
> Ale at ale.org
> http://www.ale.org/mailman/listinfo/ale




More information about the Ale mailing list