tags:

views:

142

answers:

4

I'm making a script parser in python and I'm a little stuck. I am not quite sure how to parse a line for all its functions (or even just one function at a time) and then search for a function with that name, and if it exists, execute that function short of writing a massive list if elif else block....

EDIT

This is for my own scripting language that i'm making. its nothing very complex, but i have a standard library of 8 functions or so that i need to be able to be run, how can i parse a line and run the function named in the line?

A: 

Take a look at PLY. It should help you keep your parser specification clean.

PEZ
+2  A: 

Check out PyParsing, it allows for definition of the grammar directly in Python code:

Assuming a function call is just somename():

>>> from pyparsing import *
>>> grammar = Word(alphas + "_",  alphanums + "_")("func_name") + "()" + StringEnd()
>>> grammar.parseString("ab()\n")["func_name"]
"ab"
Torsten Marek
this is helpful but how would i then run the function?
The.Anti.9
Cf. the answer by nosklo for that.
Torsten Marek
A: 

It all depends on what code you are parsing.

If you are parsing Python syntax, use the parser module from Python: http://docs.python.org/library/parser.html

A quite complete list of parser libraries available for Python you can find at: http://nedbatchelder.com/text/python-parsers.html

Adam Dziendziel
+3  A: 

Once you get the name of the function, use a dispatch dict to run the function:

def mysum(...): ...
def myotherstuff(...): ...

# create dispatch dict:
myfunctions = {'sum': mysum, 'stuff': myotherstuff}

# run your parser:
function_name, parameters = parse_result(line)

# run the function:
myfunctions[function_name](parameters)

Alternatively create a class with the commands:

class Commands(object):
    def do_sum(self, ...): ...
    def do_stuff(self, ...): ...
    def run(self, funcname, params):
        getattr(self, 'do_' + funcname)(params)

cmd = Commands()
function_name, parameters = parse_result(line)
cmd.run(function_name, parameters)

You could also look at the cmd module in the stdlib to do your class. It can provide you with a command-line interface for your language, with tab command completion, automatically.

nosklo