[Chicago] Passing an expression into Python then executing it

Kumar McMillan kumar.mcmillan at gmail.com
Mon Dec 3 22:10:26 CET 2012


On Mon, Dec 3, 2012 at 2:33 PM, D Mahoney <dan at streemit.net> wrote:

> I'm working on a log file parser and have a bunch of regular expressions I
> want to watch for and for each regex I have an expression that tells me
> what re output result I want to return for analysis. For example, one of my
> instruction lines might look like:
> '(Connection closed by ([a-zA-Z0-9.-]+)', 'groups()[0]'
> What that would tell me is that after I do a re.search of the compiled
> regex against my log file line, if the input line matches the regex I want
> to return the contents of groups()[0] to the calling code.
>
> I am at a loss as to how to do this.
>
> I've been experimenting with the "compile" and "exec" commands, but
> haven't been able to figure out how to do what I'm attempting. I've also
> tried using backticks, but so far all I've been able to do is return the
> string "groups()[0]".
>

Hi Dan.
It sounds like you are on the right track. The pattern you're describing is
common but in Python we generally handle it with callbacks. So you could do
it like this:

expr = ['(Connection closed by ([a-zA-Z0-9.-]+)', processor]

Notice how instead of mapping an expression to a string of code, each
expression is mapped to a callback. The callback could look like this:

def processor(match_ob):
    return match_ob.groups()[0]

I think that would give you the same flexibility you were trying to achieve
by executing a string of code.


>
> Is there a reasonable way to do what I'm attempting, or should I look for
> a different approach?
> ______________________________**_________________
> Chicago mailing list
> Chicago at python.org
> http://mail.python.org/**mailman/listinfo/chicago<http://mail.python.org/mailman/listinfo/chicago>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20121203/b837c848/attachment.html>


More information about the Chicago mailing list