[ale] Python regex (Now: readline())
Christopher Fowler
cfowler at outpostsentinel.com
Sun Sep 10 21:17:51 EDT 2006
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.
On Sat, 2006-09-09 at 13:46 -0600, JK wrote:
> Christopher Fowler wrote:
> > I'm in the process of converting a Perl module to a Python equivalent so
> > it can be used in Python programs. I'm not exactly a pro with Python.
> > I may need a bit of help.
> >
> > One thing I love about Perl is regular expression support.
> > I'm not sure how I can do the same in Python. The issue here is that
> > I connect to a master database to get a connection string for an
> > organizational database. I now need to connect to that database.
> > Below is the string that comes from the connect_string column:
> >
> > jdbc:mysql://127.0.0.1/AC_DEMO
> >
> > In Perl I might do the following to extract what I need:
> >
> > connection_string =~ m/mysql:\/\/(.+?)/\(.+?)$/;
> > $host = $1
> > $db = $2
> >
> > Can someone tell me how I can do the equivalent in Python?
>
> http://docs.python.org/lib/module-re.html
>
> Briefly:
>
> data="Somewhere in this string is something I want."
>
> import re
>
> regex="some.*[Ii]"
> match=re.search(regex,data)
> print match.group(0)
> # Prints "something I"
>
> Further details in the referenced URL. You can, for example,
> precompile REs for performance, start searching at a
> particular location, etc. It is slightly more verbose
> than Perl, but equally flexible (I believe the same
> underlying RE lib is used in both cases).
>
> -- JK
> _______________________________________________
> Ale mailing list
> Ale at ale.org
> http://www.ale.org/mailman/listinfo/ale
More information about the Ale
mailing list