[ale] Python regex (Now: readline())
Alex LeDonne
aledonne.listmail at gmail.com
Mon Sep 11 11:21:25 EDT 2006
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.
-A
More information about the Ale
mailing list